package com.alibaba.citrus.cr.forecast.functions.forecastorder.factory;

import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.citrus.cr.common.constant.OrderFeaturesKey;
import com.alibaba.citrus.cr.common.enums.ordercenter.ForecastOrderTypeEnum;
import com.alibaba.citrus.cr.common.enums.ordercenter.SalesOrderTypeEnum;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.common.util.SpringContextUtil;
import com.alibaba.citrus.cr.forecast.functions.forecastorder.constants.ForecastConstants;
import com.alibaba.citrus.cr.forecast.functions.forecastorder.entity.ForecastOrderEntity;
import com.alibaba.citrus.cr.forecast.functions.forecastorder.entity.ForecastOrderLineEntity;
import com.alibaba.citrus.cr.forecast.repository.ForecastOrderLineQueryRepository;
import com.alibaba.citrus.cr.forecast.repository.ForecastOrderQueryRepository;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.esdegrade.dto.GetEsDegradeValueResponse;
import com.epoch.app.bcorder.esdegrade.service.EsDegradeService;
import com.epoch.app.bcorder.model.dto.BaselineQueryScItemByPageFromDbRequest;
import com.epoch.app.bcorder.model.dto.SearchReqDTO;
import com.epoch.app.bcorder.model.dto.SearchScItemByDBWhenDegradedRequest;
import com.epoch.app.bcorder.model.dto.SearchScItemRequest;
import com.epoch.app.bcorder.platform_enhance.SaleOrderTag;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crb2btradecenter.sdo.OrderLineSDO;
import com.epoch.app.crb2btradecenter.sdo.OrderSDO;
import com.epoch.app.crb2btradecenter.sdo.PaymentInformationSDO;
import com.epoch.app.crb2btradecenter.sdo.ScItemSDO;
import com.epoch.app.crforecastsales.api.forecastorderlinequery.service.ForecastOrderLineQueryService;
import com.epoch.app.crforecastsales.api.forecastorderwrite.dto.DeleteActivityForecastRequest;
import com.epoch.app.crforecastsales.dto.request.CancelForecastOrderRequest;
import com.epoch.app.crforecastsales.dto.request.LoseFocusSaveForecastLineOrderRequest;
import com.epoch.app.crforecastsales.dto.request.*;
import com.epoch.app.crforecastsales.enums.ForecastStatusEnum;
import com.epoch.app.crforecastsales.model.dto.*;
import com.epoch.app.crforecastsales.sdo.ForecastOrderLineSDO;
import com.epoch.app.crforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.crplatformenhance.api.scitemquery.service.ScItemQueryService;
import com.epoch.app.crplatformenhance.dictionaryquery.service.DictionaryQueryService;
import com.epoch.app.crplatformenhance.model.dto.QueryDictionaryRequest;
import com.epoch.app.crpricecenter.dto.request.ActivityItemInfoRequest;
import com.epoch.app.crpricecenter.model.enums.ActivityTypeEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ForecastOrderFactory {

    private final static ArrayList<String> replenishList = Lists.newArrayList(ActivityTypeEnum.REPLENISH_LIST.getValue().split(","));
    public static final String KA_BUSINESS_UNIT_CODE = "6140A1";

    private static Log log = Log.getLogger(ForecastOrderFactory.class);
    //主单读
    private static ForecastOrderQueryRepository forecastOrderQueryRepository;
    //子订单读
    private static ForecastOrderLineQueryRepository forecastOrderLineQueryRepository;

    private static DictionaryQueryService dictionaryQueryService;
    private static ScItemQueryService scItemQueryService;

    private static ForecastOrderLineQueryService forecastOrderLineQueryService;
    private static BaseDataService baseDataService;

    private static EsDegradeService esDegradeService;

    static {
        forecastOrderQueryRepository = SpringContextUtil.getBean(ForecastOrderQueryRepository.class);
        dictionaryQueryService = SpringContextUtil.getBean(DictionaryQueryService.class);
        forecastOrderLineQueryRepository = SpringContextUtil.getBean(ForecastOrderLineQueryRepository.class);
        scItemQueryService = SpringContextUtil.getBean(ScItemQueryService.class);
        forecastOrderLineQueryService = SpringContextUtil.getBean(ForecastOrderLineQueryService.class);
        baseDataService = SpringContextUtil.getBean(BaseDataService.class);
        esDegradeService = SpringContextUtil.getBean(EsDegradeService.class);
    }

    public static List<ForecastOrderEntity> createDraft(CreateForecastOrderRequest saveForecastOrderRequest) {
        List<ForecastOrderEntity> forecastOrderEntityList = new ArrayList<>();
        List<ForecastOrderSDO> forecastOrderSDOList = saveForecastOrderRequest.getForecastOrderSDOList();
        if (CollectionUtils.isNotEmpty(forecastOrderSDOList)) {
            for (ForecastOrderSDO forecastOrderSDO : forecastOrderSDOList) {
                List<ForecastOrderLineSDO> forecastOrderLineSDOList = forecastOrderSDO.getForecastOrderLineSDOList();
                if (CollectionUtils.isNotEmpty(forecastOrderLineSDOList)) {
                    for (ForecastOrderLineSDO forecastOrderLineSDO : forecastOrderLineSDOList) {
                        String activityNumber = forecastOrderLineSDO.getActivityNumber();
                        if (StringUtils.isNotEmpty(activityNumber)) {
                            Map<String, Object> originFeatures = forecastOrderLineSDO.getFeatures();
                            if (MapUtils.isEmpty(originFeatures)) {
                                Map<String, Object> features = new HashMap<>();
                                features.put(ForecastConstants.ACTIVITY_NUMBER, activityNumber);
                                forecastOrderLineSDO.setFeatures(features);
                            } else {
                                originFeatures.put(ForecastConstants.ACTIVITY_NUMBER, activityNumber);
                            }
                        }
                    }
                }
                forecastOrderSDO.setVaildBeginTime(forecastOrderSDO.getVaildBeginTime() == null ? new Date() : forecastOrderSDO.getVaildBeginTime());
                forecastOrderSDO.setModifierName(saveForecastOrderRequest.getOperatorName());
                forecastOrderSDO.setModifierId(saveForecastOrderRequest.getOperatorId());
//                forecastOrderSDO.setCreatorName(saveForecastOrderRequest.getOperatorName());
//                forecastOrderSDO.setCreatorId(saveForecastOrderRequest.getOperatorId());
                ForecastOrderEntity forecastOrderEntity = ForecastOrderEntity.of(forecastOrderSDO);
                forecastOrderEntityList.add(forecastOrderEntity);
            }

        }
        return forecastOrderEntityList;
    }

    public static List<ForecastOrderEntity> submitForecast(SubmitForecastRequest submitForecastRequest) {
        List<ForecastOrderSDO> forecastOrderSDOList = submitForecastRequest.getForecastOrderSDOList();
        if (CollectionUtils.isEmpty(forecastOrderSDOList)) {
            return null;
        }
        List<ForecastOrderEntity> forecastOrderEntities = new ArrayList<>(forecastOrderSDOList.size());
        forecastOrderSDOList.forEach(forecastOrderSDO -> forecastOrderEntities.add(convertToForecastEntity(forecastOrderSDO)));
        return forecastOrderEntities;
    }

    private static ForecastOrderEntity convertToForecastEntity(ForecastOrderSDO forecastOrderSDO) {
        ForecastOrderEntity forecastOrderEntity = ForecastOrderEntity.of(forecastOrderSDO);
        return forecastOrderEntity;
    }

    public static ForecastOrderEntity queryForecastOrderDetail(
            QueryForecastOrderDetailRequest queryForecastOrderDetailRequest) {
        ForecastOrderSDO forecastOrderSDO = new ForecastOrderSDO();
        forecastOrderSDO.setId(queryForecastOrderDetailRequest.getId());
        //ForecastOrderSDO forecastOrderSDO = queryForecastOrderDetailRequest.getForecastOrderSDO();
        ForecastOrderEntity forecastOrderEntity = ForecastOrderEntity.of(forecastOrderSDO);
        //        ForecastOrderSDO sdo = forecastOrderQueryRepository.load(pk);
        return forecastOrderEntity;
    }

    public static List<ForecastOrderEntity> cancelForecastOrder(CancelForecastOrderRequest cancelForecastOrderRequest) {
        ArrayList<ForecastOrderEntity> forecastOrderEntityList = new ArrayList<>();
        List<String> ids = cancelForecastOrderRequest.getIds();
        for (String id : ids) {
            ForecastOrderSDO forecastOrderDTO = new ForecastOrderSDO();
            forecastOrderDTO.setId(id);
            ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.queyrDetail(forecastOrderDTO.getId());
            ForecastOrderEntity forecastOrderEntity = ForecastOrderEntity.of(forecastOrderSDO);
            forecastOrderEntityList.add(forecastOrderEntity);
        }
        return forecastOrderEntityList;
    }

    public static List<ForecastOrderEntity> modifyDraft(ModifyForecastOrderRequest modifyForecastOrderRequest) {
        List<ForecastOrderEntity> forecastOrderEntityList = new ArrayList<>();
        List<ForecastOrderSDO> forecastOrderSDOList = modifyForecastOrderRequest.getForecastOrderSDOList();
        for (ForecastOrderSDO forecastOrderSDO : forecastOrderSDOList) {
            ForecastOrderEntity forecastOrderEntity = ForecastOrderEntity.of(forecastOrderSDO);
            forecastOrderEntityList.add(forecastOrderEntity);
        }
        return forecastOrderEntityList;
    }

    /**
     * 根据主订单Id 查询订单头与所有明细信息 提交与查询列表使用
     *
     * @param pk 主订单id
     * @return
     */
    public static ForecastOrderEntity loadById(String pk) {
        ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.load(pk);
        forecastOrderLineQueryRepository.queryByOrderId(forecastOrderSDO);
        ForecastOrderEntity forecastOrderEntity = ForecastOrderEntity.of(forecastOrderSDO);
        return forecastOrderEntity;
    }

    public static ForecastOrderEntity loseFocusSave(
            LoseFocusSaveForecastLineOrderRequest loseFocusSaveForecastLineOrderRequest) {

        return null;
    }

    /**
     * 批量创建预报单（ 这里有拆单逻辑，需要特别注意 ）
     * @param ids 预报单id
     * @return 预报单实体
     */
    public static List<ForecastOrderEntity> batchCreateForecastOrder(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        List<ForecastOrderEntity> forecastOrderEntityList = new ArrayList<>();
        //查询子订单的信息
        PageResult<List<ForecastOrderLineSDO>> pageResult = forecastOrderLineQueryRepository.batchLoadList(ids);
        Map<String, List<ForecastOrderLineSDO>> collect = Nullable.stream(pageResult.getContent()).collect(Collectors.groupingBy(ForecastOrderLineSDO::getMainOrderId));
        for (Map.Entry<String, List<ForecastOrderLineSDO>> entry : collect.entrySet()) {
            String forecastOrderId = entry.getKey();
            List<ForecastOrderLineSDO> forecastOrderLineSDOList = entry.getValue();

            ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.queyrDetail(forecastOrderId);

            List<ForecastOrderLineSDO> newForecastOrderLineList = new ArrayList<>();
            int i = 1;
            for (ForecastOrderLineSDO it : forecastOrderLineSDOList) {
                String str = JSONObject.toJSONString(it);
                ForecastOrderLineSDO lineSDO = JSONObject.parseObject(str, ForecastOrderLineSDO.class);
                lineSDO.setSerialNumber(String.valueOf(i * 10));
//                newForecastOrderLineList.add(lineSDO);

                List<ActivitySDO> activityListValid = new ArrayList<>();
                Map<String, Object> features = lineSDO.getFeatures();
                if (Objects.nonNull(features) && Objects.nonNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {

                    List<ActivitySDO> activitySDOS = JSONObject.parseArray(JSON.toJSONString(lineSDO.getFeatures().get(ForecastConstants.ACTIVITY_DETAILS)), ActivitySDO.class);
                    if (CollectionUtils.isNotEmpty(activitySDOS)) {
                        Map<String, ActivitySDO> activitySDOMap = new HashMap<>();
                        activitySDOS.forEach(activitySDO -> {
                            if (activitySDO.getIsSelect()) {
                                activitySDOMap.put(activitySDO.getActivityCode(), activitySDO);
                            }
                        });
                        //拼接活动名称
                        List<String> activityNames = activitySDOS.stream().filter(activitySDO -> activitySDO.getIsSelect()==true).map(ActivitySDO::getActivityName).collect(Collectors.toList());
                        String activityName = activityNames.stream().collect(Collectors.joining("/"));
                        lineSDO.setActivityName(activityName);
                        //            拼接活动码
                        List<String> activityCodes = activitySDOS.stream().filter(activitySDO -> activitySDO.getIsSelect()==true).map(ActivitySDO::getActivityCode).collect(Collectors.toList());
                        String activityCode = activityCodes.stream().collect(Collectors.joining("/"));
                        lineSDO.setActivityCode(activityCode);
                        features.put(ForecastConstants.ACTIVITY_DETAILS,activitySDOMap.values());
                        lineSDO.setFeatures(features);
                        log.info("创建预报单时候的活动信息={}", activitySDOMap);
                        boolean haveSpecialPrice = false;
                        for (ActivitySDO activitySDO : activitySDOMap.values()) {

                            activitySDOMap.put(activitySDO.getActivityCode(), activitySDO);
                            if ("ZS03".equals(activitySDO.getActivityType())) {

                                if (!Objects.isNull(features.get("activityInventory"))) {
                                    int activityRemain = Integer.parseInt(String.valueOf(features.get("activityInventory")));
                                    Integer predictReplyAmount = lineSDO.getPredictReplyAmount();
                                    //活动量小于预计回复数量 拆主单，特价活动部分满足
                                    if (activityRemain < predictReplyAmount && activityRemain != 0) {
                                        haveSpecialPrice = true;

                                        String s = JSONObject.toJSONString(lineSDO);
                                        ForecastOrderLineSDO lineSdoNoActivity = JSONObject.parseObject(s, ForecastOrderLineSDO.class);
                                        lineSdoNoActivity.setPredictReplyAmount(predictReplyAmount - activityRemain);
                                        lineSdoNoActivity.setSerialNumber("10");
                                        //移除活动信息
//                                        Map<String,ActivitySDO> map = new HashMap<>();
//                                        BeanUtils.copyProperties(activitySDOMap,map);
//                                        map.remove(activitySDO.getActivityCode());
                                        Map<String, String> newFeatures = lineSdoNoActivity.getFeatures();
//                                        newFeatures.put(ForecastConstants.ACTIVITY_DETAILS,JSON.toJSONString(map.values()));
                                        newFeatures.remove(ForecastConstants.ACTIVITY_DETAILS);
                                        newFeatures.remove(ForecastConstants.ACTIVITY_NUMBER);
                                        lineSdoNoActivity.setActivityPrice(null);
                                        lineSdoNoActivity.setActivityName(null);
                                        lineSdoNoActivity.setActivityType(null);
                                        lineSdoNoActivity.setActivityNumber(null);
                                        lineSdoNoActivity.setActivityCode(null);
                                        lineSdoNoActivity.setFeatures(newFeatures);

                                        //构建无活动的entity
                                        List<ForecastOrderLineSDO> forecastOrderLineSDOListNoActivityList = new ArrayList<>();
                                        forecastOrderLineSDOListNoActivityList.add(lineSdoNoActivity);
                                        ForecastOrderSDO forecastOrderSDONoActivity = JSONObject.parseObject(JSON.toJSONString(forecastOrderSDO), ForecastOrderSDO.class);
                                        forecastOrderSDONoActivity.setForecastOrderLineSDOList(forecastOrderLineSDOListNoActivityList);
                                        ForecastOrderEntity forecastOrderEntityNoActivity = ForecastOrderEntity.of(forecastOrderSDONoActivity);
                                        forecastOrderEntityList.add(forecastOrderEntityNoActivity);

                                        //下面是有占用成功的部分特价订单
                                        lineSDO.setActivityPrice(activitySDO.getSpecialOfferPrice()==0L?null:activitySDO.getSpecialOfferPrice());
                                        lineSDO.setPredictReplyAmount(activityRemain);
//                                        lineSDO.setActivityNumber(activitySDO.getActivityTermid());
//                                        lineSDO.setActivityName(activitySDO.getActivityName());
//                                        lineSDO.setActivityType(activitySDO.getActivityType());
//                                        lineSDO.setActivityCode(activitySDO.getActivityCode());
//                                        lineSDO.setSerialNumber(String.valueOf(i * 10));
                                    } else {
                                        if (activityRemain == 0) {
                                            //特价活动为0
                                            lineSDO.setPredictReplyAmount(predictReplyAmount - activityRemain);
                                            lineSDO.setSerialNumber(String.valueOf(i * 10));
                                            //移除特价信息
                                            Map<String, ActivitySDO> map = new HashMap<>();
                                            BeanUtils.copyProperties(activitySDOMap, map);
                                            map.remove(activitySDO.getActivityCode());
                                            Map<String, Object> newFeatures = lineSDO.getFeatures();
                                            newFeatures.put(ForecastConstants.ACTIVITY_DETAILS, map.values());
//                                            newFeatures.remove(ForecastConstants.ACTIVITY_NUMBER);
//                                            newFeatures.remove(ForecastConstants.ACTIVITY_DETAILS);
                                            lineSDO.setFeatures(newFeatures);
                                            lineSDO.setActivityNumber(activitySDO.getActivityTermid());
//                                            lineSDO.setActivityName(activitySDO.getActivityName());
                                            lineSDO.setActivityType(activitySDO.getActivityType());
//                                            lineSDO.setActivityCode(activitySDO.getActivityCode());

                                        } else {
                                            haveSpecialPrice = true;
                                            //特价活动完全满足
                                            lineSDO.setActivityNumber(activitySDO.getActivityTermid());
//                                            lineSDO.setActivityName(activitySDO.getActivityName());
                                            lineSDO.setActivityType(activitySDO.getActivityType());
                                            lineSDO.setPredictReplyAmount(predictReplyAmount);
//                                            lineSDO.setSerialNumber(String.valueOf(i * 10));
                                            lineSDO.setActivityPrice(activitySDO.getSpecialOfferPrice()==0L?null:activitySDO.getSpecialOfferPrice());
//                                            lineSDO.setActivityCode(activitySDO.getActivityCode());
                                        }
                                    }
                                    //带活动sdo指set一回
//                                    newForecastOrderLineList.add(lineSDO);
                                } else {
//                                    newForecastOrderLineList.add(lineSDO);
                                }
                            }

                            //判断赠品活动
                            if (Objects.equals(activitySDO.getActivityType(), "ZS02")) {
                                List<GiftSDO> giftList = activitySDO.getChooseGiftList();
                                String giftLine = JSONObject.toJSONString(lineSDO);

                                if (!CollectionUtils.isEmpty(giftList)) {
                                    int lineNo = 1;
                                    for (GiftSDO giftSDO : giftList) {
                                        ForecastOrderLineSDO giftLineSdo = JSONObject.parseObject(giftLine, ForecastOrderLineSDO.class);
                                        giftLineSdo.setActivityNumber(activitySDO.getActivityTermid());
                                        giftLineSdo.setScItemId(giftSDO.getScItemId());
                                        giftLineSdo.setPredictReplyAmount(giftSDO.getGiftNumber());
                                        giftLineSdo.setUnitPrice(giftSDO.getGiftPrice());
                                        giftLineSdo.setSaleUnit(giftSDO.getGiftSalesUnit());
                                        giftLineSdo.setScItemTitle(giftSDO.getGiftName());
                                        giftLineSdo.setSaleUnitCode(giftSDO.getGiftSalesUnitCode());
                                        Map<String, Object> objectMap = new HashMap<>();
                                        objectMap.put("giftsMainSingle", giftLineSdo.getSerialNumber());
                                        objectMap.put("giftFlag", "gift");
//                                        赠品上添加活动 id 和活动项目 ID
                                        List<ActivitySDO> activitySDOList=new ArrayList<>();
                                        activitySDOList.add(activitySDO);
                                        objectMap.put(ForecastConstants.ACTIVITY_DETAILS,activitySDOList);
                                        giftLineSdo.setFeatures(objectMap);
//                                        giftLineSdo.getFeatures().put("giftsMainSingle", giftLineSdo.getSerialNumber());
//                                        giftLineSdo.getFeatures().put("giftFlag","gift");
                                        int serialNumber = Integer.parseInt(giftLineSdo.getSerialNumber());
                                        giftLineSdo.setSerialNumber(String.valueOf(serialNumber + (lineNo++)));
                                        giftLineSdo.setActivityName(null);
                                        giftLineSdo.setActivityType(null);
                                        giftLineSdo.setActivityNumber(null);
                                        giftLineSdo.setActivityCode(null);
                                        giftLineSdo.setActivityPrice(null);
                                        giftLineSdo.setTotalActivityFee(null);

                                        Result<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> listResultS = new Result<>();

                                        // es 降级开关 若开关开启，需要走db降级查询 开关未开启，走原有逻辑
                                        GetEsDegradeValueResponse esDegradeValue = esDegradeService.getEsDegradeValue();
                                        if (esDegradeValue != null && esDegradeValue.getResult()){
                                            BaselineQueryScItemByPageFromDbRequest baselineQueryScItemByPageFromDbRequest = BaselineQueryScItemByPageFromDbRequest.builder().build();
                                            baselineQueryScItemByPageFromDbRequest.setOutId(giftLineSdo.getScItemId());
                                            Object o = baseDataService.baselineQueryScItemByPageFromDb(baselineQueryScItemByPageFromDbRequest);
                                            JSONArray jsonArray = JSONObject.parseObject(JSONObject.toJSONString(o)).getJSONObject("result").getJSONObject("result").getJSONArray("searchResult");
                                            if (jsonArray != null && !jsonArray.isEmpty()){
                                                JSONObject jsonObject = jsonArray.getJSONObject(0);
                                                List<com.epoch.app.bcorder.model.dto.ScItemSDO> lists = new ArrayList<>();
                                                com.epoch.app.bcorder.model.dto.ScItemSDO scItemSDO = JSONObject.parseObject(jsonObject.toJSONString(), com.epoch.app.bcorder.model.dto.ScItemSDO.class);
                                                lists.add(scItemSDO);
                                                listResultS.setResult(lists);
                                                listResultS.setSuccess(true);
                                            }

                                        } else {
                                            // 补充赠品行的货品信息， 代码暂时先不优化
                                            SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
                                            SearchReqDTO searchReqDTO = new SearchReqDTO();
                                            List<String> list = new ArrayList<>();
                                            list.add(giftLineSdo.getScItemId());
                                            searchReqDTO.setScItemIds(list);
                                            searchScItemRequest.setSearchReqDTO(searchReqDTO);
                                            log.info("赠品查询商品属性的入参：", searchScItemRequest);
                                            listResultS = baseDataService.searchScItem(searchScItemRequest);
                                        }

                                        if (listResultS.isSuccess() && CollectionUtils.isNotEmpty(listResultS.getResult())) {
                                            com.epoch.app.bcorder.model.dto.ScItemSDO scItemSDO = listResultS.getResult().get(0);
                                            giftLineSdo.setScItemOutCode(scItemSDO.getOuterId());
                                            giftLineSdo.setScItemTitle(scItemSDO.getTitle());
                                            giftLineSdo.setScItemId(scItemSDO.getScItemId());
                                            Map<String, String> featuresObj = scItemSDO.getFeatures();
                                            if (MapUtils.isNotEmpty(features)) {
                                                String unitName = featuresObj.get("unit");
                                                String unitCode = featuresObj.get("unitName");
                                                if (StringUtils.isNotBlank(unitName)) {
                                                    giftLineSdo.setInventoryUnit(unitName);
                                                }
                                                if (StringUtils.isNotBlank(unitCode)) {
                                                    giftLineSdo.setInventoryUnitCode(unitCode);
                                                }
                                            }
                                            //todo 接口未取到库存单位名称
                                            QuerySaleUnitRequest querySaleUnitRequest = QuerySaleUnitRequest.builder().scItemId(scItemSDO.getScItemId()).build();
                                            querySaleUnitRequest.setInventoryUnit(giftLineSdo.getInventoryUnit());
                                            querySaleUnitRequest.setInventoryUnitCode(giftLineSdo.getInventoryUnitCode());
                                            querySaleUnitRequest.setUnitConvert("1");
                                            Result<List<SelectCombox>> querySaleUnitList = forecastOrderLineQueryService.querySaleUnitList(querySaleUnitRequest);
                                            if (querySaleUnitList.isSuccess() && Objects.nonNull(querySaleUnitList.getResult())) {
                                                List<SelectCombox> result = querySaleUnitList.getResult();
                                                Map<String, SelectCombox> unitMap = new HashMap<>();
                                                Nullable.stream(result).forEach(t -> {
                                                    unitMap.put(t.getValue(), t);
                                                });
                                                SelectCombox selected = unitMap.get(giftLineSdo.getSaleUnit());
                                                if (selected != null) {
                                                    giftLineSdo.setSaleUnit(selected.getLabel());
                                                    giftLineSdo.setUnitConvert(selected.getExt());
                                                }

                                                SelectCombox inventoryMap = unitMap.get(giftLineSdo.getInventoryUnit());
                                                if (inventoryMap != null) {
                                                    giftLineSdo.setInventoryUnit(inventoryMap.getLabel());
                                                }
                                            }
                                        }
                                        newForecastOrderLineList.add(giftLineSdo);
                                    }

                                    //移除特价
                                    if(!haveSpecialPrice) {
                                        lineSDO.setActivityPrice(null);
                                        lineSDO.setTotalActivityFee(null);
                                    }
                                }
//                                newForecastOrderLineList.add(lineSDO);

                            }
                            if (replenishList.contains(activitySDO.getActivityType())) {
                                String activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? "" : features.get(ForecastConstants.ACTIVITY_NUMBER).toString();
                                lineSDO.setActivityPrice(null);
                                lineSDO.setTotalActivityFee(null);
                                lineSDO.setActivityNumber(activityNumber);
                            }
                        }
                    }

                } else {
                    String activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? ""
                            : String.valueOf(features.get(ForecastConstants.ACTIVITY_NUMBER));
                    lineSDO.setActivityNumber(activityNumber);
                }
                if ("03".equals(forecastOrderSDO.getOrderType())) {
                    //代表
                    if (StringUtils.isNotEmpty(lineSDO.getActivityCode()) && MapUtils.isNotEmpty(features)) {
                        if (Objects.isNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {
                            List<ActivitySDO> activitySDOs = new ArrayList<>();
                            ActivitySDO activitySDO = new ActivitySDO();
                            String activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? "" :
                                    String.valueOf(features.get(ForecastConstants.ACTIVITY_NUMBER));
                            activitySDO.setActivityTermid(activityNumber);
                            activitySDO.setActivityCode(lineSDO.getActivityCode());
                            activitySDO.setActivityType("ZS42");
                            activitySDO.setIsSelect(true);
                            activitySDOs.add(activitySDO);
                            features.put(ForecastConstants.ACTIVITY_DETAILS, activitySDOs);
                            lineSDO.setActivityPrice(null);
                            lineSDO.setTotalActivityFee(null);
                            lineSDO.setFeatures(features);
                        }
                    }
                }

                if (StringUtils.isNotEmpty(lineSDO.getActivityCode()) && MapUtils.isNotEmpty(features)
                        && Objects.nonNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {

                    List<ActivitySDO> activitySDOList = JSONObject.parseArray(JSON.toJSONString(features.get(ForecastConstants.ACTIVITY_DETAILS)), ActivitySDO.class);
                    List<ActivitySDO> choseActivitySDS = activitySDOList.stream().filter(activitySDO -> activitySDO.getIsSelect() == true).collect(Collectors.toList());

                    if (CollectionUtils.isEmpty(choseActivitySDS)) {
                        lineSDO.setActivityCode(null);
                        lineSDO.setActivityName(null);
                        lineSDO.setActivityPrice(null);
                        lineSDO.setTotalActivityFee(null);

                    }
                }
                //原sdo指set一回
                newForecastOrderLineList.add(lineSDO);
                i++;
            }
            forecastOrderSDO.setForecastOrderLineSDOList(newForecastOrderLineList);
            ForecastOrderEntity of = ForecastOrderEntity.of(forecastOrderSDO);
            forecastOrderEntityList.add(of);

        }
        log.info("生成销售订单构造Entity：{}", JSONObject.toJSONString(forecastOrderEntityList));
        return forecastOrderEntityList;

    }


    public static List<ForecastOrderEntity> batchCreateForecastOrder(ForecastOrderEntity forecastOrderEntity) {
//        if (CollectionUtils.isEmpty(ids)) {
//            return null;
//        }
        log.info("666---拆单的入参==="+JSON.toJSONString(forecastOrderEntity));
        List<ForecastOrderEntity> forecastOrderEntityList = new ArrayList<>();
//        //查询子订单的信息
//        PageResult<List<ForecastOrderLineSDO>> pageResult = forecastOrderLineQueryRepository.batchLoadList(ids);
////        Map<String, List<ForecastOrderLineSDO>> collect = Nullable.stream(pageResult.getContent()).collect(Collectors.groupingBy(ForecastOrderLineSDO::getMainOrderId));
////        for (Map.Entry<String, List<ForecastOrderLineSDO>> entry : collect.entrySet()) {
////            String forecastOrderId = entry.getKey();
        if (forecastOrderEntity.getForecastOrderSDO() == null || CollectionUtils.isEmpty(forecastOrderEntity.getForecastOrderSDO().getForecastOrderLineSDOList())) {
            return null;
        }
        List<ForecastOrderLineSDO> forecastOrderLineSDOList = forecastOrderEntity.getForecastOrderSDO().getForecastOrderLineSDOList();

        ForecastOrderSDO forecastOrderSDO = forecastOrderEntity.getForecastOrderSDO();//forecastOrderQueryRepository.queyrDetail(forecastOrderLineSDOList.get(0).getMainOrderId());

        List<ForecastOrderLineSDO> newForecastOrderLineList = new ArrayList<>();
        int i = 1;
        for (ForecastOrderLineSDO it : forecastOrderLineSDOList) {
            String str = JSONObject.toJSONString(it);
            ForecastOrderLineSDO lineSDO = JSONObject.parseObject(str, ForecastOrderLineSDO.class);
            lineSDO.setFrontLineNo(lineSDO.getSerialNumber());
            lineSDO.setSerialNumber(String.valueOf(i * 10));
            Map<String, Object> features = lineSDO.getFeatures();
            if (Objects.nonNull(features) && Objects.nonNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {

                List<ActivitySDO> activitySDOS = JSONObject.parseArray(JSON.toJSONString(lineSDO.getFeatures().get(ForecastConstants.ACTIVITY_DETAILS)), ActivitySDO.class);
                if (CollectionUtils.isNotEmpty(activitySDOS)) {
                    Map<String, ActivitySDO> activitySDOMap = new HashMap<>();
                    activitySDOS.forEach(activitySDO -> {
                        if (activitySDO.getIsSelect()) {
                            activitySDOMap.put(activitySDO.getActivityCode(), activitySDO);
                        }
                    });
                    //拼接活动名称
                    List<String> activityNames = activitySDOS.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityName).collect(Collectors.toList());
                    String activityName = String.join("/", activityNames);
                    lineSDO.setActivityName(activityName);
                    //            拼接活动码
                    List<String> activityCodes = activitySDOS.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityCode).collect(Collectors.toList());
                    String activityCode = String.join("/", activityCodes);
                    lineSDO.setActivityCode(activityCode);
                    features.put(ForecastConstants.ACTIVITY_DETAILS, activitySDOMap.values());
                    lineSDO.setFeatures(features);
                    log.info("创建预报单时候的活动信息={}", activitySDOMap);
                    boolean haveSpecialPrice = false;
                    for (ActivitySDO activitySDO : activitySDOMap.values()) {

                        if (Objects.nonNull(activitySDO.getDisableChooseFlag())&&activitySDO.getDisableChooseFlag()){
                            continue;
                        }
                        activitySDOMap.put(activitySDO.getActivityCode(), activitySDO);
                        if ("ZS03".equals(activitySDO.getActivityType())) {

                            if (!Objects.isNull(features.get("activityInventory"))) {
                                int activityRemain = Integer.parseInt(String.valueOf(features.get("activityInventory")));
                                Integer predictReplyAmount = lineSDO.getPredictReplyAmount();
                                //活动量小于预计回复数量 拆主单，特价活动部分满足
                                if (activityRemain < predictReplyAmount && activityRemain != 0) {
                                    haveSpecialPrice = true;

                                    String s = JSONObject.toJSONString(lineSDO);
                                    ForecastOrderLineSDO lineSdoNoActivity = JSONObject.parseObject(s, ForecastOrderLineSDO.class);
                                    lineSdoNoActivity.setPredictReplyAmount(predictReplyAmount - activityRemain);
                                    lineSdoNoActivity.setSerialNumber("10");
                                    //移除活动信息
//                                        Map<String,ActivitySDO> map = new HashMap<>();
//                                        BeanUtils.copyProperties(activitySDOMap,map);
//                                        map.remove(activitySDO.getActivityCode());
                                    Map<String, String> newFeatures = lineSdoNoActivity.getFeatures();
//                                        newFeatures.put(ForecastConstants.ACTIVITY_DETAILS,JSON.toJSONString(map.values()));
                                    newFeatures.remove(ForecastConstants.ACTIVITY_DETAILS);
                                    newFeatures.remove(ForecastConstants.ACTIVITY_NUMBER);
                                    lineSdoNoActivity.setActivityPrice(null);
                                    lineSdoNoActivity.setActivityName(null);
                                    lineSdoNoActivity.setActivityType(null);
                                    lineSdoNoActivity.setActivityNumber(null);
                                    lineSdoNoActivity.setActivityCode(null);
                                    lineSdoNoActivity.setFeatures(newFeatures);

                                    //构建无活动的entity
                                    List<ForecastOrderLineSDO> forecastOrderLineSDOListNoActivityList = new ArrayList<>();
                                    forecastOrderLineSDOListNoActivityList.add(lineSdoNoActivity);
                                    ForecastOrderSDO forecastOrderSDONoActivity = JSONObject.parseObject(JSON.toJSONString(forecastOrderSDO), ForecastOrderSDO.class);
                                    forecastOrderSDONoActivity.setForecastOrderLineSDOList(forecastOrderLineSDOListNoActivityList);
                                    ForecastOrderEntity forecastOrderEntityNoActivity = ForecastOrderEntity.of(forecastOrderSDONoActivity);
                                    forecastOrderEntityList.add(forecastOrderEntityNoActivity);

                                    //下面是有占用成功的部分特价订单
                                    lineSDO.setActivityPrice(activitySDO.getSpecialOfferPrice() == 0L ? null : activitySDO.getSpecialOfferPrice());
                                    lineSDO.setPredictReplyAmount(activityRemain);
//                                        lineSDO.setActivityNumber(activitySDO.getActivityTermid());
//                                        lineSDO.setActivityName(activitySDO.getActivityName());
//                                        lineSDO.setActivityType(activitySDO.getActivityType());
//                                        lineSDO.setActivityCode(activitySDO.getActivityCode());
//                                        lineSDO.setSerialNumber(String.valueOf(i * 10));
                                } else {
                                    if (activityRemain == 0) {
                                        //特价活动为0
                                        lineSDO.setPredictReplyAmount(predictReplyAmount - activityRemain);
                                        lineSDO.setSerialNumber(String.valueOf(i * 10));
                                        //移除特价信息
                                        Map<String, ActivitySDO> map = new HashMap<>();
                                        BeanUtils.copyProperties(activitySDOMap, map);
                                        map.remove(activitySDO.getActivityCode());
                                        Map<String, Object> newFeatures = lineSDO.getFeatures();
                                        newFeatures.put(ForecastConstants.ACTIVITY_DETAILS, map.values());
//                                            newFeatures.remove(ForecastConstants.ACTIVITY_NUMBER);
//                                            newFeatures.remove(ForecastConstants.ACTIVITY_DETAILS);
                                        lineSDO.setFeatures(newFeatures);
                                        lineSDO.setActivityNumber(activitySDO.getActivityTermid());
//                                            lineSDO.setActivityName(activitySDO.getActivityName());
                                        lineSDO.setActivityType(activitySDO.getActivityType());
//                                            lineSDO.setActivityCode(activitySDO.getActivityCode());

                                    } else {
                                        haveSpecialPrice = true;
                                        //特价活动完全满足
                                        lineSDO.setActivityNumber(activitySDO.getActivityTermid());
//                                            lineSDO.setActivityName(activitySDO.getActivityName());
                                        lineSDO.setActivityType(activitySDO.getActivityType());
                                        lineSDO.setPredictReplyAmount(predictReplyAmount);
//                                            lineSDO.setSerialNumber(String.valueOf(i * 10));
                                        lineSDO.setActivityPrice(activitySDO.getSpecialOfferPrice() == 0L ? null : activitySDO.getSpecialOfferPrice());
//                                            lineSDO.setActivityCode(activitySDO.getActivityCode());
                                    }
                                }
                                //带活动sdo指set一回
//                                    newForecastOrderLineList.add(lineSDO);
                            } else {
//                                    newForecastOrderLineList.add(lineSDO);
                            }
                        }

                        //判断赠品活动
                        if (Objects.equals(activitySDO.getActivityType(), "ZS02")) {
                            List<GiftSDO> giftList = activitySDO.getChooseGiftList();
                            String giftLine = JSONObject.toJSONString(lineSDO);

                            if (!CollectionUtils.isEmpty(giftList)) {
                                int lineNo = 1;
                                for (GiftSDO giftSDO : giftList) {
                                    ForecastOrderLineSDO giftLineSdo = JSONObject.parseObject(giftLine, ForecastOrderLineSDO.class);
                                    giftLineSdo.setActivityNumber(activitySDO.getActivityTermid());
                                    giftLineSdo.setScItemId(giftSDO.getScItemId());
                                    giftLineSdo.setPredictReplyAmount(giftSDO.getGiftNumber());
                                    giftLineSdo.setUnitPrice(giftSDO.getGiftPrice());
                                    giftLineSdo.setSaleUnit(giftSDO.getGiftSalesUnit());
                                    giftLineSdo.setScItemTitle(giftSDO.getGiftName());
                                    giftLineSdo.setSaleUnitCode(giftSDO.getGiftSalesUnitCode());
                                    giftLineSdo.setInventoryUnitCode(giftSDO.getGiftUnitCode());
                                    giftLineSdo.setInventoryUnit(giftSDO.getGiftUint());
                                    //add by myw,for gift order remark add 20221018
                                    giftLineSdo.setDetailRemark(giftSDO.getRemark());
                                    Map<String, Object> objectMap = new HashMap<>();
                                    objectMap.put("giftsMainSingle", giftLineSdo.getSerialNumber());
                                    objectMap.put("giftFlag", "gift");
                                    //add by myw,for gift disable choose 20221102
                                    objectMap.put("giftDisable", giftSDO.getGiftDisable());
//                                        赠品上添加活动 id 和活动项目 ID
                                    List<ActivitySDO> activitySDOList = new ArrayList<>();
                                    activitySDOList.add(activitySDO);
                                    objectMap.put(ForecastConstants.ACTIVITY_DETAILS, activitySDOList);
                                    giftLineSdo.setFeatures(objectMap);
//                                        giftLineSdo.getFeatures().put("giftsMainSingle", giftLineSdo.getSerialNumber());
//                                        giftLineSdo.getFeatures().put("giftFlag","gift");
                                    int serialNumber = Integer.parseInt(giftLineSdo.getSerialNumber());
                                    giftLineSdo.setSerialNumber(String.valueOf(serialNumber + (lineNo++)));
                                    giftLineSdo.setActivityName(null);
                                    giftLineSdo.setActivityType(null);
                                    giftLineSdo.setActivityNumber(null);
                                    giftLineSdo.setActivityCode(null);
                                    giftLineSdo.setActivityPrice(null);
                                    giftLineSdo.setTotalActivityFee(null);

                                    // 补充赠品行的货品信息， 代码暂时先不优化
                                    SearchScItemByDBWhenDegradedRequest searchScItemRequest = new SearchScItemByDBWhenDegradedRequest();
                                    SearchReqDTO searchReqDTO = new SearchReqDTO();
                                    List<String> list = new ArrayList<>();
                                    list.add(giftLineSdo.getScItemId());
                                    searchReqDTO.setScItemIds(list);
                                    searchScItemRequest.setSearchReqDTO(searchReqDTO);
                                    log.info("赠品查询商品属性的入参：", searchScItemRequest);
                                    //支持es降级查询db
                                    Result<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> listResultS = baseDataService.searchScItemByDBWhenDegraded(searchScItemRequest);

                                    if (listResultS.isSuccess() && CollectionUtils.isNotEmpty(listResultS.getResult())) {
                                        com.epoch.app.bcorder.model.dto.ScItemSDO scItemSDO = listResultS.getResult().get(0);
                                        giftLineSdo.setScItemOutCode(scItemSDO.getOuterId());
                                        giftLineSdo.setScItemTitle(scItemSDO.getTitle());
                                        giftLineSdo.setScItemId(scItemSDO.getScItemId());
                                        Map<String, String> featuresObj = scItemSDO.getFeatures();
                                        if (MapUtils.isNotEmpty(features)) {
                                            String unitName = featuresObj.get("unit");
                                            String unitCode = featuresObj.get("unitName");
                                            if (StringUtils.isNotBlank(unitName)) {
                                                giftLineSdo.setInventoryUnit(unitName);
                                            }
                                            if (StringUtils.isNotBlank(unitCode)) {
                                                giftLineSdo.setInventoryUnitCode(unitCode);
                                            }
                                        }
                                        //todo 接口未取到库存单位名称
                                        QuerySaleUnitRequest querySaleUnitRequest = QuerySaleUnitRequest.builder().scItemId(scItemSDO.getScItemId()).build();
                                        querySaleUnitRequest.setInventoryUnit(giftLineSdo.getInventoryUnit());
                                        querySaleUnitRequest.setInventoryUnitCode(giftLineSdo.getInventoryUnitCode());
                                        querySaleUnitRequest.setUnitConvert("1");
                                        Result<List<SelectCombox>> querySaleUnitList = forecastOrderLineQueryService.querySaleUnitList(querySaleUnitRequest);
                                        if (querySaleUnitList.isSuccess() && Objects.nonNull(querySaleUnitList.getResult())) {
                                            List<SelectCombox> result = querySaleUnitList.getResult();
                                            Map<String, SelectCombox> unitMap = new HashMap<>();
                                            Nullable.stream(result).forEach(t -> {
                                                unitMap.put(t.getValue(), t);
                                            });
                                            SelectCombox selected = unitMap.get(giftLineSdo.getSaleUnitCode());
                                            if (selected != null) {
                                                giftLineSdo.setSaleUnit(selected.getLabel());
                                                giftLineSdo.setUnitConvert(selected.getExt());
                                            }

                                            SelectCombox inventoryMap = unitMap.get(giftLineSdo.getInventoryUnit());
                                            if (inventoryMap != null) {
                                                giftLineSdo.setInventoryUnit(inventoryMap.getLabel());
                                            }
                                        }
                                    }
                                    newForecastOrderLineList.add(giftLineSdo);
                                }

                                //移除特价
                                if (!haveSpecialPrice) {
                                    lineSDO.setActivityPrice(null);
                                    lineSDO.setTotalActivityFee(null);
                                }
                            }
//                                newForecastOrderLineList.add(lineSDO);


                        }
                        //todo 多种补货活动需要支持
                        if (replenishList.contains(activitySDO.getActivityType())) {
                            String activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? "" : features.get(ForecastConstants.ACTIVITY_NUMBER).toString();
                            lineSDO.setActivityPrice(null);
                            lineSDO.setTotalActivityFee(null);
                            lineSDO.setActivityNumber(activityNumber);
                        }
                    }
                }

            } else {
                String activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? ""
                        : String.valueOf(features.get(ForecastConstants.ACTIVITY_NUMBER));
                lineSDO.setActivityNumber(activityNumber);
            }
            if ("03".equals(forecastOrderSDO.getOrderType())) {
                //代表
                if (StringUtils.isNotEmpty(lineSDO.getActivityCode()) && MapUtils.isNotEmpty(features)) {
                    if (Objects.isNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {
                        List<ActivitySDO> activitySDOs = new ArrayList<>();
                        ActivitySDO activitySDO = new ActivitySDO();
                        String activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? "" :
                                String.valueOf(features.get(ForecastConstants.ACTIVITY_NUMBER));
                        activitySDO.setActivityTermid(activityNumber);
                        activitySDO.setActivityCode(lineSDO.getActivityCode());
                        activitySDO.setActivityType("ZS42");
                        activitySDO.setIsSelect(true);
                        activitySDOs.add(activitySDO);
                        features.put(ForecastConstants.ACTIVITY_DETAILS, activitySDOs);
                        lineSDO.setActivityPrice(null);
                        lineSDO.setTotalActivityFee(null);
                        lineSDO.setFeatures(features);
                    }
                }
            }

            if (StringUtils.isNotEmpty(lineSDO.getActivityCode()) && MapUtils.isNotEmpty(features)
                    && Objects.nonNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {

                List<ActivitySDO> activitySDOList = JSONObject.parseArray(JSON.toJSONString(features.get(ForecastConstants.ACTIVITY_DETAILS)), ActivitySDO.class);
                List<ActivitySDO> choseActivitySDS = activitySDOList.stream().filter(activitySDO -> activitySDO.getIsSelect() == true).collect(Collectors.toList());

                if (CollectionUtils.isEmpty(choseActivitySDS)) {
                    lineSDO.setActivityCode(null);
                    lineSDO.setActivityName(null);
                    lineSDO.setActivityPrice(null);
                    lineSDO.setTotalActivityFee(null);

                }
            }

            //非赠品标识
            if (MapUtils.isNotEmpty(lineSDO.getFeatures())){
                lineSDO.getFeatures().put("giftFlag","X");
            }
            //原sdo指set一回
            newForecastOrderLineList.add(lineSDO);
            i++;
        }
        forecastOrderSDO.setForecastOrderLineSDOList(newForecastOrderLineList);
        ForecastOrderEntity of = ForecastOrderEntity.of(forecastOrderSDO);
        forecastOrderEntityList.add(of);


        log.info("----拆单后的结果：生成销售订单构造Entity：{}", JSONObject.toJSONString(forecastOrderEntityList));
        return forecastOrderEntityList;

    }

    public static List<ForecastOrderEntity> batchSyncCreateForecastOrder(ForecastOrderEntity forecastOrderEntity, Map<String, String> fulfillmentMap) {
        log.info("666---拆单的入参==="+JSON.toJSONString(forecastOrderEntity));
        List<ForecastOrderEntity> forecastOrderEntityList = new ArrayList<>();
        if (forecastOrderEntity.getForecastOrderSDO() == null || CollectionUtils.isEmpty(forecastOrderEntity.getForecastOrderSDO().getForecastOrderLineSDOList())) {
            return null;
        }
        List<ForecastOrderLineSDO> forecastOrderLineSDOList = forecastOrderEntity.getForecastOrderSDO().getForecastOrderLineSDOList();

        ForecastOrderSDO forecastOrderSDO = forecastOrderEntity.getForecastOrderSDO();

        String orderBizId = forecastOrderSDO.getOrderBizId();
        if (Objects.nonNull(fulfillmentMap)&&fulfillmentMap.containsKey(orderBizId)){
            forecastOrderSDO.setFulfillmentTypeCode(fulfillmentMap.get(orderBizId));
        }
        //重置期望交货日期
        if (forecastOrderSDO.getBusinessUnitCode().equals(KA_BUSINESS_UNIT_CODE)){
            forecastOrderSDO.setCustomerExpectTDate(DateUtils.getFirstTime(new Date()));
        }

        List<ForecastOrderLineSDO> newForecastOrderLineList = new ArrayList<>();
        int i = 1;
        for (ForecastOrderLineSDO it : forecastOrderLineSDOList) {
            String str = JSONObject.toJSONString(it);
            ForecastOrderLineSDO lineSDO = JSONObject.parseObject(str, ForecastOrderLineSDO.class);
            lineSDO.setFrontLineNo(lineSDO.getSerialNumber());
            lineSDO.setSerialNumber(String.valueOf(i * 10));
            Map<String, Object> features = lineSDO.getFeatures();
            String bizFeaturesStr = lineSDO.getBizFeatures();
            if (StringUtils.isNotBlank(bizFeaturesStr)){
                Map<String,String> bizFeaturesMap =  JSONObject.parseObject(bizFeaturesStr, Map.class);
                if (bizFeaturesMap.containsKey("predictReplyWarehouseCode")){
                    lineSDO.setShippingWarehouseCode(bizFeaturesMap.get("predictReplyWarehouseCode"));
                    forecastOrderSDO.setShippingWarehouseCode(bizFeaturesMap.get("predictReplyWarehouseCode"));
//                    forecastOrderSDO.setWareHouseCode(forecastOrderSDO.getShippingWarehouseCode());
                }
                if (bizFeaturesMap.containsKey("predictReplyWarehouseName")){
                    lineSDO.setShippingWarehouseName(bizFeaturesMap.get("predictReplyWarehouseName"));
                    forecastOrderSDO.setShippingWarehouseName(bizFeaturesMap.get("predictReplyWarehouseName"));
//                    forecastOrderSDO.setWareHouseName(forecastOrderSDO.getShippingWarehouseName());
                }
            }

            if (Objects.nonNull(features) && Objects.nonNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {

                List<ActivitySDO> activitySDOS = JSONObject.parseArray(JSON.toJSONString(lineSDO.getFeatures().get(ForecastConstants.ACTIVITY_DETAILS)), ActivitySDO.class);
                if (CollectionUtils.isNotEmpty(activitySDOS)) {
                    Map<String, ActivitySDO> activitySDOMap = new HashMap<>();
                    activitySDOS.forEach(activitySDO -> {
                        if (activitySDO.getIsSelect()) {
                            activitySDOMap.put(activitySDO.getActivityCode(), activitySDO);
                        }
                    });
                    //拼接活动名称
                    List<String> activityNames = activitySDOS.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityName).collect(Collectors.toList());
                    String activityName = String.join("/", activityNames);
                    lineSDO.setActivityName(activityName);
                    //            拼接活动码
                    List<String> activityCodes = activitySDOS.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityCode).collect(Collectors.toList());
                    String activityCode = String.join("/", activityCodes);
                    lineSDO.setActivityCode(activityCode);
                    features.put(ForecastConstants.ACTIVITY_DETAILS, activitySDOMap.values());
                    lineSDO.setFeatures(features);
                    log.info("创建预报单时候的活动信息={}", activitySDOMap);
                    boolean haveSpecialPrice = false;
                    for (ActivitySDO activitySDO : activitySDOMap.values()) {

                        if (Objects.nonNull(activitySDO.getDisableChooseFlag())&&activitySDO.getDisableChooseFlag()){
                            continue;
                        }
                        activitySDOMap.put(activitySDO.getActivityCode(), activitySDO);
                        if ("ZS03".equals(activitySDO.getActivityType())) {

                            if (!Objects.isNull(features.get("activityInventory"))) {
                                int activityRemain = Integer.parseInt(String.valueOf(features.get("activityInventory")));
                                Integer predictReplyAmount = lineSDO.getPredictReplyAmount();
                                //活动量小于预计回复数量 拆主单，特价活动部分满足
                                if (activityRemain < predictReplyAmount && activityRemain != 0) {
                                    haveSpecialPrice = true;

                                    String s = JSONObject.toJSONString(lineSDO);
                                    ForecastOrderLineSDO lineSdoNoActivity = JSONObject.parseObject(s, ForecastOrderLineSDO.class);
                                    lineSdoNoActivity.setPredictReplyAmount(predictReplyAmount - activityRemain);
                                    lineSdoNoActivity.setSerialNumber("10");
                                    //移除活动信息
//                                        Map<String,ActivitySDO> map = new HashMap<>();
//                                        BeanUtils.copyProperties(activitySDOMap,map);
//                                        map.remove(activitySDO.getActivityCode());
                                    Map<String, String> newFeatures = lineSdoNoActivity.getFeatures();
//                                        newFeatures.put(ForecastConstants.ACTIVITY_DETAILS,JSON.toJSONString(map.values()));
                                    newFeatures.remove(ForecastConstants.ACTIVITY_DETAILS);
                                    newFeatures.remove(ForecastConstants.ACTIVITY_NUMBER);
                                    lineSdoNoActivity.setActivityPrice(null);
                                    lineSdoNoActivity.setActivityName(null);
                                    lineSdoNoActivity.setActivityType(null);
                                    lineSdoNoActivity.setActivityNumber(null);
                                    lineSdoNoActivity.setActivityCode(null);
                                    lineSdoNoActivity.setFeatures(newFeatures);

                                    //构建无活动的entity
                                    List<ForecastOrderLineSDO> forecastOrderLineSDOListNoActivityList = new ArrayList<>();
                                    forecastOrderLineSDOListNoActivityList.add(lineSdoNoActivity);
                                    ForecastOrderSDO forecastOrderSDONoActivity = JSONObject.parseObject(JSON.toJSONString(forecastOrderSDO), ForecastOrderSDO.class);
                                    forecastOrderSDONoActivity.setForecastOrderLineSDOList(forecastOrderLineSDOListNoActivityList);
                                    ForecastOrderEntity forecastOrderEntityNoActivity = ForecastOrderEntity.of(forecastOrderSDONoActivity);
                                    forecastOrderEntityList.add(forecastOrderEntityNoActivity);

                                    //下面是有占用成功的部分特价订单
                                    lineSDO.setActivityPrice(activitySDO.getSpecialOfferPrice() == 0L ? null : activitySDO.getSpecialOfferPrice());
                                    lineSDO.setPredictReplyAmount(activityRemain);
//                                        lineSDO.setActivityNumber(activitySDO.getActivityTermid());
//                                        lineSDO.setActivityName(activitySDO.getActivityName());
//                                        lineSDO.setActivityType(activitySDO.getActivityType());
//                                        lineSDO.setActivityCode(activitySDO.getActivityCode());
//                                        lineSDO.setSerialNumber(String.valueOf(i * 10));
                                } else {
                                    if (activityRemain == 0) {
                                        //特价活动为0
                                        lineSDO.setPredictReplyAmount(predictReplyAmount - activityRemain);
                                        lineSDO.setSerialNumber(String.valueOf(i * 10));
                                        //移除特价信息
                                        Map<String, ActivitySDO> map = new HashMap<>();
                                        BeanUtils.copyProperties(activitySDOMap, map);
                                        map.remove(activitySDO.getActivityCode());
                                        Map<String, Object> newFeatures = lineSDO.getFeatures();
                                        newFeatures.put(ForecastConstants.ACTIVITY_DETAILS, map.values());
//                                            newFeatures.remove(ForecastConstants.ACTIVITY_NUMBER);
//                                            newFeatures.remove(ForecastConstants.ACTIVITY_DETAILS);
                                        lineSDO.setFeatures(newFeatures);
                                        lineSDO.setActivityNumber(activitySDO.getActivityTermid());
//                                            lineSDO.setActivityName(activitySDO.getActivityName());
                                        lineSDO.setActivityType(activitySDO.getActivityType());
//                                            lineSDO.setActivityCode(activitySDO.getActivityCode());

                                    } else {
                                        haveSpecialPrice = true;
                                        //特价活动完全满足
                                        lineSDO.setActivityNumber(activitySDO.getActivityTermid());
//                                            lineSDO.setActivityName(activitySDO.getActivityName());
                                        lineSDO.setActivityType(activitySDO.getActivityType());
                                        lineSDO.setPredictReplyAmount(predictReplyAmount);
//                                            lineSDO.setSerialNumber(String.valueOf(i * 10));
                                        lineSDO.setActivityPrice(activitySDO.getSpecialOfferPrice() == 0L ? null : activitySDO.getSpecialOfferPrice());
//                                            lineSDO.setActivityCode(activitySDO.getActivityCode());
                                    }
                                }
                                //带活动sdo指set一回
//                                    newForecastOrderLineList.add(lineSDO);
                            } else {
//                                    newForecastOrderLineList.add(lineSDO);
                            }
                        }

                        //判断赠品活动
                        if (Objects.equals(activitySDO.getActivityType(), "ZS02")) {
                            List<GiftSDO> giftList = activitySDO.getChooseGiftList();
                            String giftLine = JSONObject.toJSONString(lineSDO);

                            if (!CollectionUtils.isEmpty(giftList)) {
                                int lineNo = 1;
                                for (GiftSDO giftSDO : giftList) {
                                    ForecastOrderLineSDO giftLineSdo = JSONObject.parseObject(giftLine, ForecastOrderLineSDO.class);
                                    giftLineSdo.setActivityNumber(activitySDO.getActivityTermid());
                                    giftLineSdo.setScItemId(giftSDO.getScItemId());
                                    giftLineSdo.setPredictReplyAmount(giftSDO.getGiftNumber());
                                    giftLineSdo.setUnitPrice(giftSDO.getGiftPrice());
                                    giftLineSdo.setSaleUnit(giftSDO.getGiftSalesUnit());
                                    giftLineSdo.setScItemTitle(giftSDO.getGiftName());
                                    giftLineSdo.setSaleUnitCode(giftSDO.getGiftSalesUnitCode());
                                    giftLineSdo.setInventoryUnitCode(giftSDO.getGiftUnitCode());
                                    giftLineSdo.setInventoryUnit(giftSDO.getGiftUint());
                                    //add by myw,for gift order remark add 20221018
                                    giftLineSdo.setDetailRemark(giftSDO.getRemark());
                                    Map<String, Object> objectMap = new HashMap<>();
                                    objectMap.put("giftsMainSingle", giftLineSdo.getSerialNumber());
                                    objectMap.put("giftFlag", "gift");
                                    //add by myw,for gift disable choose 20221102
                                    objectMap.put("giftDisable", giftSDO.getGiftDisable());
//                                        赠品上添加活动 id 和活动项目 ID
                                    List<ActivitySDO> activitySDOList = new ArrayList<>();
                                    activitySDOList.add(activitySDO);
                                    objectMap.put(ForecastConstants.ACTIVITY_DETAILS, activitySDOList);
                                    giftLineSdo.setFeatures(objectMap);
//                                        giftLineSdo.getFeatures().put("giftsMainSingle", giftLineSdo.getSerialNumber());
//                                        giftLineSdo.getFeatures().put("giftFlag","gift");
                                    int serialNumber = Integer.parseInt(giftLineSdo.getSerialNumber());
                                    giftLineSdo.setSerialNumber(String.valueOf(serialNumber + (lineNo++)));
                                    giftLineSdo.setActivityName(null);
                                    giftLineSdo.setActivityType(null);
                                    giftLineSdo.setActivityNumber(null);
                                    giftLineSdo.setActivityCode(null);
                                    giftLineSdo.setActivityPrice(null);
                                    giftLineSdo.setTotalActivityFee(null);

                                    // 补充赠品行的货品信息， 代码暂时先不优化
                                    SearchScItemByDBWhenDegradedRequest searchScItemRequest = new SearchScItemByDBWhenDegradedRequest();
                                    SearchReqDTO searchReqDTO = new SearchReqDTO();
                                    List<String> list = new ArrayList<>();
                                    list.add(giftLineSdo.getScItemId());
                                    searchReqDTO.setOuterIdList(list);
                                    searchScItemRequest.setSearchReqDTO(searchReqDTO);
                                    log.info("赠品查询商品属性的入参:{}", JSONObject.toJSONString(searchScItemRequest));
                                    //支持es降级查询db
                                    Result<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> listResultS = baseDataService.searchScItemByDBWhenDegraded(searchScItemRequest);

                                    if (listResultS.isSuccess() && CollectionUtils.isNotEmpty(listResultS.getResult())) {
                                        com.epoch.app.bcorder.model.dto.ScItemSDO scItemSDO = listResultS.getResult().get(0);
                                        giftLineSdo.setScItemOutCode(scItemSDO.getOuterId());
                                        giftLineSdo.setScItemTitle(scItemSDO.getTitle());
                                        giftLineSdo.setScItemId(scItemSDO.getScItemId());
                                        Map<String, String> featuresObj = scItemSDO.getFeatures();
                                        if (MapUtils.isNotEmpty(features)) {
                                            String unitName = featuresObj.get("unit");
                                            String unitCode = featuresObj.get("unitName");
                                            if (StringUtils.isNotBlank(unitName)) {
                                                giftLineSdo.setInventoryUnit(unitName);
                                            }
                                            if (StringUtils.isNotBlank(unitCode)) {
                                                giftLineSdo.setInventoryUnitCode(unitCode);
                                            }
                                        }
                                        //todo 接口未取到库存单位名称
                                        QuerySaleUnitRequest querySaleUnitRequest = QuerySaleUnitRequest.builder().scItemId(scItemSDO.getScItemId()).build();
                                        querySaleUnitRequest.setInventoryUnit(giftLineSdo.getInventoryUnit());
                                        querySaleUnitRequest.setInventoryUnitCode(giftLineSdo.getInventoryUnitCode());
                                        querySaleUnitRequest.setUnitConvert("1");
                                        Result<List<SelectCombox>> querySaleUnitList = forecastOrderLineQueryService.querySaleUnitList(querySaleUnitRequest);
                                        if (querySaleUnitList.isSuccess() && Objects.nonNull(querySaleUnitList.getResult())) {
                                            List<SelectCombox> result = querySaleUnitList.getResult();
                                            Map<String, SelectCombox> unitMap = new HashMap<>();
                                            Nullable.stream(result).forEach(t -> {
                                                unitMap.put(t.getValue(), t);
                                            });
                                            SelectCombox selected = unitMap.get(giftLineSdo.getSaleUnitCode());
                                            if (selected != null) {
                                                giftLineSdo.setSaleUnit(selected.getLabel());
                                                giftLineSdo.setUnitConvert(selected.getExt());
                                            }

                                            SelectCombox inventoryMap = unitMap.get(giftLineSdo.getInventoryUnit());
                                            if (inventoryMap != null) {
                                                giftLineSdo.setInventoryUnit(inventoryMap.getLabel());
                                            }
                                        }
                                    }
                                    newForecastOrderLineList.add(giftLineSdo);
                                }

                                //移除特价
                                if (!haveSpecialPrice) {
                                    lineSDO.setActivityPrice(null);
                                    lineSDO.setTotalActivityFee(null);
                                }
                            }
                        }
                        //todo 多种补货活动需要支持
                        if (replenishList.contains(activitySDO.getActivityType())) {
                            String activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? "" : features.get(ForecastConstants.ACTIVITY_NUMBER).toString();
                            lineSDO.setActivityPrice(null);
                            lineSDO.setTotalActivityFee(null);
                            lineSDO.setActivityNumber(activityNumber);
                        }
                    }
                }

            } else {
                String activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? ""
                        : String.valueOf(features.get(ForecastConstants.ACTIVITY_NUMBER));
                lineSDO.setActivityNumber(activityNumber);
            }
            if ("03".equals(forecastOrderSDO.getOrderType())) {
                //代表
                if (StringUtils.isNotEmpty(lineSDO.getActivityCode()) && MapUtils.isNotEmpty(features)) {
                    if (Objects.isNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {
                        List<ActivitySDO> activitySDOs = new ArrayList<>();
                        ActivitySDO activitySDO = new ActivitySDO();
                        String activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? "" :
                                String.valueOf(features.get(ForecastConstants.ACTIVITY_NUMBER));
                        activitySDO.setActivityTermid(activityNumber);
                        activitySDO.setActivityCode(lineSDO.getActivityCode());
                        activitySDO.setActivityType("ZS42");
                        activitySDO.setIsSelect(true);
                        activitySDOs.add(activitySDO);
                        features.put(ForecastConstants.ACTIVITY_DETAILS, activitySDOs);
                        lineSDO.setActivityPrice(null);
                        lineSDO.setTotalActivityFee(null);
                        lineSDO.setFeatures(features);
                    }
                }
            }

            if (StringUtils.isNotEmpty(lineSDO.getActivityCode()) && MapUtils.isNotEmpty(features)
                    && Objects.nonNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {

                List<ActivitySDO> activitySDOList = JSONObject.parseArray(JSON.toJSONString(features.get(ForecastConstants.ACTIVITY_DETAILS)), ActivitySDO.class);
                List<ActivitySDO> choseActivitySDS = activitySDOList.stream().filter(activitySDO -> activitySDO.getIsSelect() == true).collect(Collectors.toList());

                if (CollectionUtils.isEmpty(choseActivitySDS)) {
                    lineSDO.setActivityCode(null);
                    lineSDO.setActivityName(null);
                    lineSDO.setActivityPrice(null);
                    lineSDO.setTotalActivityFee(null);

                }
            }

            //非赠品标识
            if (MapUtils.isNotEmpty(lineSDO.getFeatures())){
                lineSDO.getFeatures().put("giftFlag","X");
            }
            //原sdo指set一回
            newForecastOrderLineList.add(lineSDO);
            i++;
        }
        forecastOrderSDO.setForecastOrderLineSDOList(newForecastOrderLineList);
        ForecastOrderEntity of = ForecastOrderEntity.of(forecastOrderSDO);
        forecastOrderEntityList.add(of);


        log.info("----拆单后的结果：生成销售订单构造Entity：{}", JSONObject.toJSONString(forecastOrderEntityList));
        return forecastOrderEntityList;
    }

    /**
     * 创建销售单
     *
     * @param forecastOrderEntities 预报单实体列表
     * @return
     */
    public static List<OrderSDO> batchCreateOrder(List<ForecastOrderEntity> forecastOrderEntities,String sequenceNo) {
        List<OrderSDO> orderSDOS = new ArrayList<>();
        for (ForecastOrderEntity forecastOrderEntity : forecastOrderEntities) {
            ForecastOrderSDO forecastOrderSDO = forecastOrderEntity.getForecastOrderSDO();
            OrderSDO orderSDO = toOrderSDO(forecastOrderSDO,sequenceNo);
//            DeliverOrderSDO deliverOrderSDO= toDeliverOrderSDO(forecastOrderSDO);
            List<ForecastOrderLineSDO> forecastOrderLineSDOList = forecastOrderSDO.getForecastOrderLineSDOList();
//            List<DeliveryOrderDetailSDO> list=new ArrayList<>();
            List<OrderLineSDO> orderLineSDOS = new ArrayList<>();
            for (ForecastOrderLineSDO forecastOrderLineSDO : forecastOrderLineSDOList) {
                OrderLineSDO orderLineSDO = toOrderLineSDO(forecastOrderLineSDO, forecastOrderSDO,sequenceNo);
//                DeliveryOrderDetailSDO deliveryOrderDetailSDO=toDeliveryOrderDetailSDO(forecastOrderLineSDO);
//                list.add(deliveryOrderDetailSDO);
                orderLineSDOS.add(orderLineSDO);
            }
//            deliverOrderSDO.setDeliveryOrderDetailSDOS(list);
//            orderSDO.setDeliverOrderSDO(deliverOrderSDO);
            orderSDO.setOrderLineSDOS(orderLineSDOS);
            orderSDOS.add(orderSDO);
        }
        log.info("生成销售订单入参request：{}", JSONObject.toJSONString(orderSDOS));
        return orderSDOS;
    }

    /**
     * 创建销售单
     *
     * @param forecastOrderEntities 预报单实体列表
     * @return
     */
    public static List<OrderSDO> batchCreateOrder(List<ForecastOrderEntity> forecastOrderEntities, ConfirmForecastRequest confirmForecastRequest) {
        List<OrderSDO> orderSDOS = new ArrayList<>();
        if (CollectionUtils.isEmpty(forecastOrderEntities)) {
            return orderSDOS;
        }

        ApiContext apiContext = confirmForecastRequest.getApiContext();
        for (ForecastOrderEntity forecastOrderEntity : forecastOrderEntities) {
            ForecastOrderSDO forecastOrderSDO = forecastOrderEntity.getForecastOrderSDO();
            //转换订单模型
            OrderSDO orderSDO = toOrderSDO(forecastOrderSDO, confirmForecastRequest.getSequenceNo());
            orderSDO.setCreatorId(apiContext.getEmployeeId());
            orderSDO.setCreatorCode(confirmForecastRequest.getOperatorCode());
            orderSDO.setCreatorName(apiContext.getEmployeeName());
//            orderSDO.setModifierId(apiContext.getEmployeeId());
//            orderSDO.setModifierCode(confirmForecastRequest.getOperatorCode());
//            orderSDO.setModifierName(apiContext.getEmployeeName());

            //注释信息拼接
            String remark = (StringUtils.isBlank(forecastOrderSDO.getRemark()) ? "" : forecastOrderSDO.getRemark()) + (StringUtils.isBlank(forecastOrderSDO.getAddRemark()) ? "" : forecastOrderSDO.getAddRemark());
            orderSDO.setRemark(remark);

            List<ForecastOrderLineSDO> forecastOrderLineSDOList = forecastOrderSDO.getForecastOrderLineSDOList();
            List<OrderLineSDO> orderLineSDOS = new ArrayList<>();
            for (ForecastOrderLineSDO forecastOrderLineSDO : forecastOrderLineSDOList) {
                //转换订明细模型
                OrderLineSDO orderLineSDO = toOrderLineSDO(forecastOrderLineSDO, forecastOrderSDO, confirmForecastRequest.getSequenceNo());
                orderLineSDOS.add(orderLineSDO);
            }
            orderSDO.setOrderLineSDOS(orderLineSDOS);
            orderSDOS.add(orderSDO);
        }
        log.info("生成销售订单入参request：{}", JSONObject.toJSONString(orderSDOS));
        return orderSDOS;
    }

    /**
     * 生成销售子单行
     *
     * @param source           预报子单
     * @param forecastOrderSDO 预报主单
     * @return
     */
    public static OrderLineSDO toOrderLineSDO(ForecastOrderLineSDO source, ForecastOrderSDO forecastOrderSDO, String sequenceNo) {
        if (source == null) {
            return null;
        }
        OrderLineSDO target = new OrderLineSDO();
        target.setShouldPayFee(source.getShouldPayFee() == null ? 0L : source.getShouldPayFee());
        if (source.getActivityPrice() != null && source.getPredictReplyAmount() != null) {
            target.setActualPaidFee(source.getActivityPrice() * source.getPredictReplyAmount());
        }
        target.setSerialNumber(source.getSerialNumber());
        //target.setOrderLineTag(source.getOrder);
        target.setBizCode(source.getBizCode());
        target.setTenantId(source.getTenantId());
        target.setCustomerCode(source.getCustomerCode());
        target.setStatus(source.getStatus());
        target.setSyncVersion(source.getSyncVersion());

        target.setActivityName(source.getActivityName());
        target.setActivityCode(source.getActivityCode());
        target.setActivityTermId(source.getActivityNumber());

        target.setFrontOrderLineId(source.getId().toString());
        target.setRemark(source.getDetailRemark());

        target.setRefuseReasonName(source.getRefuseReason());
        target.setRefuseReasonCode(source.getRefuseReasonCode());
        target.setSerialNumber(source.getSerialNumber());
        /** 预报订单类型编码 */
        Map<String, String> map = new HashMap<>();
        String FRONT_ORDER_LINE_TYPE = "frontOrderLineType";
        if (MapUtils.isNotEmpty(source.getFeatures())&&Objects.nonNull(source.getFeatures().get("giftFlag"))){
            map.put("giftFlag", String.valueOf(source.getFeatures().get("giftFlag")));
        }
        if (Objects.nonNull(source.getFeatures().get("giftsMainSingle"))) {
            map.put("giftsMainSingle", source.getFeatures().get("giftsMainSingle").toString());
            map.put("giftFlag", "gift");
        }
        if (Objects.nonNull(source.getFeatures().get("giftsMainSingle"))) {
            map.put("giftDisable",source.getFeatures().get("giftDisable").toString());
        }
        map.put("forecastSubId", String.valueOf(source.getId()));
        map.put("forecastQuantity", source.getQuantity());
        map.put(ForecastConstants.ACTIVITY_NUMBER, source.getActivityNumber());
        map.put(ForecastConstants.SEQUENCE_NO, sequenceNo);
        map.put(OrderFeaturesKey.SOURCE_UNIT, source.getSourceUnit());
        map.put(OrderFeaturesKey.SOURCE_QUANTITY, String.valueOf(source.getSourceQuantity()));
        map.put(OrderFeaturesKey.SOURCE_PRICE, String.valueOf(source.getSourcePrice()));

        if (Objects.nonNull(source.getFeatures().get(ForecastConstants.ACTIVITY_DETAILS))) {
            map.put(ForecastConstants.ACTIVITY_DETAILS, JSON.toJSONString(source.getFeatures().get(ForecastConstants.ACTIVITY_DETAILS)));
        }
        map.put(FRONT_ORDER_LINE_TYPE, forecastOrderSDO.getOrderType());
        // 冗余预报单明细ID到features里，订单中心的订单从features里取预报单明细ID进行活动释放
        map.put(OrderFeaturesKey.FORECAST_ORDER_LINE_ID, source.getId().toString());

        target.setFeatures(map);

        ScItemSDO scItemSDO = new ScItemSDO();
        scItemSDO.setActivityPrice(source.getActivityPrice());
        scItemSDO.setQuantity(source.getPredictReplyAmount());
        scItemSDO.setScItemTitle(source.getScItemTitle());
        scItemSDO.setSaleUnit(source.getSaleUnitCode());
        scItemSDO.setSaleUnitName(source.getSaleUnit());
        scItemSDO.setInventoryUnitCode(source.getInventoryUnitCode());
        scItemSDO.setInventoryUnitName(source.getInventoryUnit());
        scItemSDO.setUnitConvert(source.getUnitConvert());
        if (source.getUnitPrice() != null) {
            scItemSDO.setUnitPrice(source.getUnitPrice());
        }
        if (!ObjectUtils.isEmpty(source.getGoodsProductationTime())) {
            scItemSDO.setProductationTime(source.getGoodsProductationTime() == null ? null : DateUtils.parse(source.getGoodsProductationTime()));
        }
        scItemSDO.setScItemId(source.getScItemId());
        //添加新的字段 start
        scItemSDO.setScItemOutCode(source.getScItemOutCode());
        scItemSDO.setCategoryCode(source.getCategoryCode());
        scItemSDO.setCategoryDesc(source.getCategoryDesc());
        scItemSDO.setCategoryChildCode(source.getCategoryChildCode());
        scItemSDO.setCategoryChildDesc(source.getCategoryChildDesc());
        scItemSDO.setFirstCategoryCode(source.getFirstCategoryCode());
        scItemSDO.setFirstCategoryDesc(source.getFirstCategoryDesc());
        scItemSDO.setSecondCategoryCode(source.getSecondCategoryCode());
        scItemSDO.setSecondCategoryDesc(source.getSecondCategoryDesc());
        //一盘货新增字段
        scItemSDO.setConfirmQuantity(source.getConfirmQuantity());
        scItemSDO.setInnerProductCode(source.getInnerProductCode());
        scItemSDO.setInnerProductName(source.getInnerProductName());
        scItemSDO.setItemBarCode(source.getItemBarCode());
        //添加新的字段 end
        target.setScItemSDO(scItemSDO);

        target.setFrontOrderLineId(source.getId() == null ? null : source.getId().toString());
        target.setDeliveryFactoryCode(forecastOrderSDO.getDeliveryFactoryCode());
        target.setStockCode(forecastOrderSDO.getStockCode());
        target.setSourceLineNum(source.getSourceLineNum());
        target.setFrontLineNum(source.getFrontLineNo());
        target.setShippingWarehouseCode(source.getShippingWarehouseId());
        target.setShippingWarehouseName(source.getShippingWarehouseName());
        target.setShippingWarehouseOutCode(source.getShippingWarehouseCode());
        target.setStockConversionNum(source.getUnitConvert());
        target.setBizFeatures(source.getBizFeatures());

        return target;
    }

    public static OrderSDO toOrderSDO(ForecastOrderSDO source, String sequenceNo) {
        if (source == null) {
            return null;
        }
        OrderSDO target = new OrderSDO();
        target.setCustomerName(source.getCustomerName());
        target.setCustomerCode(source.getCustomerCode());
        target.setOrganizationCode(source.getOrganizationCode());
        target.setOrganizationName(source.getOrganizationName());
        target.setDepartmentCode(source.getSalesDepartmentCode());
        target.setDepartmentName(source.getSalesDepartmentName());
        target.setDepartmentOutCode(source.getSalesDepartmentCode());
        target.setOrderType(SalesOrderTypeEnum.STD_ORDER.getCode());
        target.setOrderTypeName(SalesOrderTypeEnum.STD_ORDER.getDesc());
        if (Objects.equals(source.getOrderType(), "02")) {
            target.setOrderType(SaleOrderTag.CAR_ORDER.getCode());
            target.setOrderTypeName(SaleOrderTag.CAR_ORDER.getDesc());
        }
        if (Objects.equals(source.getOrderType(), "03")) {
            target.setOrderType(SaleOrderTag.REPLENISH_ORDER.getCode());
            target.setOrderTypeName(SaleOrderTag.REPLENISH_ORDER.getDesc());
        }
        if (Objects.equals(source.getOrderType(), ForecastOrderTypeEnum.GROUP_FORECAST.getValue())) {
            //集团标准订单
            target.setOrderType(SalesOrderTypeEnum.GROUP_STD_ORDER.getCode());
            target.setOrderTypeName(SalesOrderTypeEnum.GROUP_STD_ORDER.getDesc());
        }
        target.setSaleChannelCode(source.getSaleChannelCode());
        target.setSaleChannelName(source.getSaleChannelName());
        target.setSaleChannelOutCode(source.getSaleChannelCode());
        target.setChannelCode(source.getChannelCode());
        target.setChannelName(source.getChannelName());
        target.setReceiveAddressCode(source.getReceiveAddressCode());
        target.setReceiveDetailAddress(source.getReceiveDetailAddress());
        target.setTransportModeCode(source.getTransportModeCode());
        target.setTransportModeName(source.getTransportModeName());
        target.setBizCode(source.getBizCode());
        target.setBusinessCode(source.getBusinessCode());
        target.setStatus(2);
        target.setProductGroupCode(source.getProductGroupCode());
        target.setProductGroupName(source.getProductGroupName());
        target.setCreateReason(source.getCreateReason());
        //target.setFeatures(source.getFeatures());
        target.setRemark(source.getRemark());
        target.setFrontOrderId(source.getId());
        target.setCustomerReferenceNumber(source.getCustomerReferenceNo());
        target.setCustomerExpectDate(source.getCustomerExpectTDate());
        target.setContactor(source.getContact());
        target.setContactorPhone(source.getContactPhone());
        target.setGmtModified(source.getGmtModified());
        PaymentInformationSDO paymentInformationSDO = new PaymentInformationSDO();
        paymentInformationSDO.setOrderTotalFee(source.getOrderTotalFee());
        target.setPaymentInformationSDO(paymentInformationSDO);
        target.setWareHouseCode(source.getWareHouseCode());
        target.setWareHouseName(source.getWareHouseName());
        //target  添加新字段start
        target.setAreaCode(source.getAreaCode());
        target.setBisUnitCode(source.getBisUnitCode());
        target.setSalesmanId(source.getSalesmanCode());
        target.setSalesmanName(source.getSalesmanName());
        target.setCustomerPrincipalId(source.getCustomerPrincipalId());
        target.setCustomerPrincipalName(source.getCustomerPrincipalName());
        target.setFromSys(source.getFromSys());
        if (Objects.nonNull(source.getBusinessType())){
            target.setBusinessType(Integer.parseInt(source.getBusinessType()));
            target.setBusinessTypeName(source.getBusinessTypeName());
        }
        target.setBusinessUnitOutCode(source.getBusinessUnitCode());
        target.setBisUnitName(source.getBusinessUnitName());
        target.setCustomerPurchaseDate(source.getCustomerPurchaseDate());
        target.setSourceOrderNo(source.getSourceOrderNo());
        target.setCreatorCode(source.getCreatorCode());
        target.setModifierCode(source.getModifierCode());
        target.setModifierName(source.getModifierName());
        target.setCreatorName2(source.getCreatorName());
        target.setModifierName2(source.getModifierName());
        target.setWareHouseOutCode(source.getShippingWarehouseCode());
        /** 预报订单业务编码 */
        String FRONT_ORDER_BIZ_ID = "frontOrderBizId";
        Map<String, String> sourceFeatures = source.getFeatures();
        Map<String, String> map = sourceFeatures == null ? new HashMap<>() : sourceFeatures;
        // 放到features
//        target.setKaSystem(source.getKaSystem());
//        target.setKaArea(source.getKaArea());
//        target.setSourceOrderDate(source.getSourceOrderDate());
        map.put(FRONT_ORDER_BIZ_ID, source.getOrderBizId());
        map.put(ForecastConstants.SEQUENCE_NO, sequenceNo);
        map.put(OrderFeaturesKey.KA_AREA, source.getKaArea());
        map.put(OrderFeaturesKey.KA_SYSTEM, source.getKaSystem());

        String sourceOrderDate = map.get(OrderFeaturesKey.SOURCE_ORDER_DATE);
        if(StringUtils.isNotBlank(sourceOrderDate)) {
            String sourceOrderTime = DateUtils.stampToDate(sourceOrderDate);
            map.put(OrderFeaturesKey.SOURCE_ORDER_TIME, sourceOrderTime);
            map.remove(OrderFeaturesKey.SOURCE_ORDER_DATE);
        }
//        if (Objects.nonNull(source.getSourceOrderDate())) {
//            map.put(ForecastConstants.SOURCE_ORDER_DATE, String.valueOf(source.getSourceOrderDate().getTime()));
//        }
        target.setFeatures(map);
        target.setPreOrderNo(source.getOrderBizId());

        // F-B销售订单相关字段
        target.setOrderBizTag(source.getOrderTag());
        target.setOrderCategoryCode(source.getOrderCategoryCode());
        target.setOrderChannelCode(source.getOrderChannelCode());
        target.setReceiveWareHouseOutCode(source.getReceiveWarehouseCode());
        target.setReceiveWareHouseName(source.getReceiveWarehouseName());
        target.setReceiveFactoryCode(source.getReceiveFactoryCode());
        target.setReceiveStockCode(source.getReceiveStockCode());
        target.setFulfillmentTypeCode(source.getFulfillmentTypeCode());
        target.setFulfillmentPriority(source.getFulfillmentPriority());
        target.setAutoFulfillment(source.getAutoFulfillment());
        target.setCustomerGrade(source.getCustomerGrade());
        target.setCustomerGroup(source.getCustomerGroup());
        target.setBizFeatures(source.getBizFeatures());

        return target;
    }

    public static  Map<String, List<ForecastOrderLineSDO>> batchRefuseForecastNew(List<RefuseForecastDetailRequest> refuseForecastDetailRequests) {
        List<String> collect = Nullable.stream(refuseForecastDetailRequests).map(it -> it.getId()).collect(Collectors.toList());
        PageResult<List<ForecastOrderLineSDO>> pageResult = forecastOrderLineQueryRepository.batchLoadList(collect);
        Map<String, List<ForecastOrderLineSDO>> forecastOrderLineMap = Nullable.stream(pageResult.getContent()).map(it -> {
            for (RefuseForecastDetailRequest refuseForecastDetailRequest : refuseForecastDetailRequests) {
                if (StringUtils.equals(refuseForecastDetailRequest.getId(), it.getId().toString())) {
                    //add by 皓晖 at 20211215 for 预报回复-批量关闭时货品明细不填写拒绝原因不进行关闭 begin
                    if (StringUtils.isEmpty(refuseForecastDetailRequest.getRefuseReasonCode())) {
                        continue;
                    }
                    //add by 皓晖 at 20211215 for 预报回复-批量关闭时货品明细不填写拒绝原因不进行关闭 end
                    it.setRefuseReason(refuseForecastDetailRequest.getRefuseReason());
                    ///拒绝原因编码查name
                    QueryDictionaryRequest queryDictionaryRequest = new QueryDictionaryRequest();
                    queryDictionaryRequest.setDictCode("refuseReason");
                    queryDictionaryRequest.setValueCode(refuseForecastDetailRequest.getRefuseReasonCode());
                    Result<String> stringResult = dictionaryQueryService.queryValueNameByCode(queryDictionaryRequest);
                    it.setRefuseReasonCode(refuseForecastDetailRequest.getRefuseReasonCode());
                    it.setRefuseReason(stringResult.getResult());
                    it.setModifierId(refuseForecastDetailRequest.getModifierId());
                    it.setModifierName(refuseForecastDetailRequest.getModifierName());
                    it.setStatus(ForecastStatusEnum.COMPLETED.getNumValue());
                }
            }
            return it;
        }).collect(Collectors.groupingBy(ForecastOrderLineSDO::getMainOrderId));
        return forecastOrderLineMap;
    }

    public static List<ForecastOrderLineEntity> batchRefuseForecast(List<RefuseForecastDetailRequest> refuseForecastDetailRequests) {
        List<String> collect = Nullable.stream(refuseForecastDetailRequests).map(it -> it.getId()).collect(Collectors.toList());
        PageResult<List<ForecastOrderLineSDO>> pageResult = forecastOrderLineQueryRepository.batchLoadList(collect);
        List<ForecastOrderLineSDO> forecastOrderLineSDOList = Nullable.stream(pageResult.getContent()).map(it -> {
            for (RefuseForecastDetailRequest refuseForecastDetailRequest : refuseForecastDetailRequests) {
                if (StringUtils.equals(refuseForecastDetailRequest.getId(), it.getId().toString())) {
                    //add by 皓晖 at 20211215 for 预报回复-批量关闭时货品明细不填写拒绝原因不进行关闭 begin
                    if (StringUtils.isEmpty(refuseForecastDetailRequest.getRefuseReasonCode())) {
                        continue;
                    }
                    //add by 皓晖 at 20211215 for 预报回复-批量关闭时货品明细不填写拒绝原因不进行关闭 end

                    it.setRefuseReason(refuseForecastDetailRequest.getRefuseReason());
                    ///拒绝原因编码查name
                    QueryDictionaryRequest queryDictionaryRequest = new QueryDictionaryRequest();
                    queryDictionaryRequest.setDictCode("refuseReason");
                    queryDictionaryRequest.setValueCode(refuseForecastDetailRequest.getRefuseReasonCode());
                    // FIXME 这里需要优化：在循环外查询一次即可
                    Result<String> stringResult = dictionaryQueryService.queryValueNameByCode(queryDictionaryRequest);
                    it.setRefuseReasonCode(refuseForecastDetailRequest.getRefuseReasonCode());
                    it.setRefuseReason(stringResult.getResult());
                    it.setModifierId(refuseForecastDetailRequest.getModifierId());
                    it.setModifierName(refuseForecastDetailRequest.getModifierName());
                    it.setStatus(ForecastStatusEnum.COMPLETED.getNumValue());
                }
            }
            return it;
        }).collect(Collectors.toList());
        List<ForecastOrderLineEntity> forecastOrderEntities = new ArrayList<>(forecastOrderLineSDOList.size());
        for (ForecastOrderLineSDO forecastOrderLineSDO : forecastOrderLineSDOList) {
            ForecastOrderLineEntity of = ForecastOrderLineEntity.of(forecastOrderLineSDO);
            forecastOrderEntities.add(of);
        }
        return forecastOrderEntities;
    }

    public static List<ForecastOrderEntity> confirmForecast(ConfirmForecastRequest confirmForecastRequest) {
        if (CollectionUtils.isEmpty(confirmForecastRequest.getIds())) {
            return new ArrayList<>();
        }
        //根据子订单id查询出所有的子订单，并转换成sdo
        PageResult<List<ForecastOrderLineSDO>> pageResult = forecastOrderLineQueryRepository.batchLoadList(confirmForecastRequest.getIds());
        log.info("pageResult子单结果:{}",JSON.toJSONString(pageResult));
        //根据主订单id进行分组
        Map<String, List<ForecastOrderLineSDO>> collect = Nullable.stream(pageResult.getContent())
                .collect(Collectors.groupingBy(ForecastOrderLineSDO::getMainOrderId));
        List<ForecastOrderSDO> forecastOrderSDOList = new ArrayList<>();
        for (String key : collect.keySet()) {
            //查询预报主单信息，并转换成sdo
            ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.queyrDetail(key, false);
            log.info("forecastOrderSDO主单结果:{}",JSON.toJSONString(forecastOrderSDO));
            List<ForecastOrderLineSDO> forecastOrderLineSDOList = collect.get(key);
            //更改修改人
            for (ForecastOrderLineSDO forecastOrderLineSDO : forecastOrderLineSDOList) {
                forecastOrderLineSDO.setModifierName(confirmForecastRequest.getOperatorName());
                forecastOrderLineSDO.setModifierId(confirmForecastRequest.getOperatorId());
                forecastOrderLineSDO.setModofierCode(confirmForecastRequest.getOperatorCode());
                forecastOrderLineSDO.setCreatorName(confirmForecastRequest.getOperatorName());
                forecastOrderLineSDO.setCreatorId(confirmForecastRequest.getOperatorId());
                forecastOrderLineSDO.setCreatorCode(confirmForecastRequest.getOperatorCode());
            }
            forecastOrderSDO.setForecastOrderLineSDOList(forecastOrderLineSDOList);
            forecastOrderSDOList.add(forecastOrderSDO);
        }

        //构造entity
        List<ForecastOrderEntity> forecastOrderEntities = new ArrayList<>(forecastOrderSDOList.size());
        forecastOrderSDOList.forEach(forecastOrderSDO -> forecastOrderEntities.add(convertToForecastEntity(forecastOrderSDO)));
        return forecastOrderEntities;
    }

    //TODO 性能优化点： 这里可以直接从内存中获取单据数据，而非重新捞取
    public static List<ForecastOrderEntity> checkActivityForecast(
            ForecastOrderActivityRequest forecastOrderActivityRequest) {
        List<String> ids = forecastOrderActivityRequest.getIds();
        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        //根据子订单id查询出所有的子订单
        PageResult<List<ForecastOrderLineSDO>> pageResult = forecastOrderLineQueryRepository.batchLoadList(ids);
        //根据主订单id进行分组
        Map<String, List<ForecastOrderLineSDO>> collect = Nullable.stream(pageResult.getContent()).collect(Collectors.groupingBy(ForecastOrderLineSDO::getMainOrderId));
        List<ForecastOrderSDO> forecastOrderSDOList = new ArrayList<>();
        for (String key : collect.keySet()) {
            ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.load(key);
            List<ForecastOrderLineSDO> forecastOrderLineSDOList = collect.get(key);
            forecastOrderSDO.setForecastOrderLineSDOList(forecastOrderLineSDOList);
            forecastOrderSDOList.add(forecastOrderSDO);
        }
        //构造entity
        List<ForecastOrderEntity> forecastOrderEntities = new ArrayList<>(forecastOrderSDOList.size());
        forecastOrderSDOList.forEach(forecastOrderSDO -> forecastOrderEntities.add(convertToForecastEntity(forecastOrderSDO)));
        return forecastOrderEntities;
    }

    public static List<ForecastOrderEntity> checkActivityForecastMemory(
            List<ForecastOrderLineSDO> forecastOrderActivityRequest) {
       // List<String> ids = forecastOrderActivityRequest.getIds();
        if (CollectionUtils.isEmpty(forecastOrderActivityRequest)) {
            return null;
        }
        //根据子订单id查询出所有的子订单
       // PageResult<List<ForecastOrderLineSDO>> pageResult = forecastOrderLineQueryRepository.batchLoadList(ids);
        //根据主订单id进行分组
        Map<String, List<ForecastOrderLineSDO>> collect = Nullable.stream(forecastOrderActivityRequest).collect(Collectors.groupingBy(ForecastOrderLineSDO::getMainOrderId));
        List<ForecastOrderSDO> forecastOrderSDOList = new ArrayList<>();
        for (String key : collect.keySet()) {
            ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.load(key);
            List<ForecastOrderLineSDO> forecastOrderLineSDOList = collect.get(key);
            forecastOrderSDO.setForecastOrderLineSDOList(forecastOrderLineSDOList);
            forecastOrderSDOList.add(forecastOrderSDO);
        }
        //构造entity
        List<ForecastOrderEntity> forecastOrderEntities = new ArrayList<>(forecastOrderSDOList.size());
        forecastOrderSDOList.forEach(forecastOrderSDO -> forecastOrderEntities.add(convertToForecastEntity(forecastOrderSDO)));
        return forecastOrderEntities;
    }

    public static ForecastOrderEntity updateActivityForecast(ForecastOrderActivityRequest forecastOrderActivityRequest, Map<String, ForecastOrderLineSDO> forecastOrderLineMap, Map<String, ForecastOrderSDO> forecastOrderSDOMap) {
        //补全活动赠品价格数据兜底逻辑
        giftPriceCompleted(forecastOrderActivityRequest);

        //这里是实体，但里面只挂了一个子单
        String forecastOrderLineId = forecastOrderActivityRequest.getForecastOrderLineId();
        if (StringUtils.isEmpty(forecastOrderLineId)) {
            return null;
        }
        //根据子订单id查询出所有的子订单
        List<ForecastOrderLineSDO> orderLineSDOList = new ArrayList<>();
        ForecastOrderLineSDO forecastOrderLineSDO = forecastOrderLineMap.get(forecastOrderLineId);
//        ForecastOrderLineSDO forecastOrderLineSDO = forecastOrderLineQueryRepository.query(forecastOrderLineId);
        String activityName = "";
        String activityCode = "";
        List<ActivitySDO> activitySDOS = new ArrayList<>();
        List<ActivitySDO> activitySDOList = new ArrayList<>();
        if (Objects.nonNull(forecastOrderActivityRequest.getGiftActivity())||Objects.nonNull(forecastOrderActivityRequest.getSpecialActivity())) {
            //赠品活动数据处理
            if (Objects.nonNull(forecastOrderActivityRequest.getGiftActivity())){
                ActivityDTO giftActivity = forecastOrderActivityRequest.getGiftActivity();
                if (giftActivity.getEnabled()
                        &&StringUtils.isNotBlank(giftActivity.getSelectedActivityCode())
                        &&CollectionUtils.isNotEmpty(giftActivity.getList())){
                            //标记选中活动
                    List<ActivitySDO> chooseGiftActivity = giftActivity.getList().stream().filter(o -> o.getActivityCode().equals(giftActivity.getSelectedActivityCode())).collect(Collectors.toList());
                    activitySDOList.addAll(chooseGiftActivity);
            }}

            //特价活动数据处理
            if (Objects.nonNull(forecastOrderActivityRequest.getSpecialActivity())){
                ActivityDTO specialActivity = forecastOrderActivityRequest.getSpecialActivity();
                if (specialActivity.getEnabled()
                        &&StringUtils.isNotBlank(specialActivity.getSelectedActivityCode())
                        &&CollectionUtils.isNotEmpty(specialActivity.getList())){
                    //标记选中活动
                    List<ActivitySDO> chooseSpecialActivity = specialActivity.getList().stream().filter(o -> o.getActivityCode().equals(specialActivity.getSelectedActivityCode())).collect(Collectors.toList());
                    activitySDOList.addAll(chooseSpecialActivity);

                }
            }
        }
        // if(CollectionUtils.isNotEmpty(activitySDOList)) {
        activitySDOList = convertActivity(activitySDOList, forecastOrderLineSDO);
        // }
        log.info("新老活动匹配，转换后的活动列表：{}", activitySDOList);
        if (CollectionUtils.isNotEmpty(activitySDOList)) {
//            拼接活动名称
            List<String> activityNames = activitySDOList.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityName).collect(Collectors.toList());
            activityName = activityNames.stream().collect(Collectors.joining("/"));

//            拼接活动码
            List<String> activityCodes = activitySDOList.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityCode).collect(Collectors.toList());
            activityCode = activityCodes.stream().collect(Collectors.joining("/"));
            boolean haveSpecialOfferPriceSelectFlag = false;
            for (ActivitySDO activitySDO : activitySDOList) {
                //修改回复数量
                forecastOrderLineSDO.setPredictReplyAmount(forecastOrderActivityRequest.getPredictReplyAmount());
                if (ActivityTypeEnum.SPECIAL_OFFER_PRICE.getValue().equals(activitySDO.getActivityType())) {
                    if (Objects.nonNull(activitySDO.getIsSelect()) && activitySDO.getIsSelect()) {
                        //修改活动金额
                        forecastOrderLineSDO.setActivityPrice(activitySDO.getSpecialOfferPrice());
                        //设置活动总金额，只有特价活动有特价 活动特价
                        if (null != activitySDO.getSpecialOfferPrice() && StringUtils.isNotEmpty(forecastOrderLineSDO.getQuantity())) {
                            forecastOrderLineSDO.setTotalActivityFee(activitySDO.getSpecialOfferPrice() * Long.parseLong(forecastOrderLineSDO.getQuantity()));
                        }
                        haveSpecialOfferPriceSelectFlag = true;
                    }
                }
                //修改活动赠品情况
                Map<String, Object> features = forecastOrderLineSDO.getFeatures();
                activitySDOS.add(activitySDO);
                features.put(ForecastConstants.ACTIVITY_TAG, 0);
            }

            if (!haveSpecialOfferPriceSelectFlag) {
                //不选中特价的时候，重置活动价和活动总金额
                removeActivityPrice(forecastOrderLineSDO);
            }

        } else {
            //不选中特价的时候，重置活动价和活动总金额
            //modify by myw,20220916 to 未选中任何活动移除所有活动信息
            removeActivityAllInfo(forecastOrderLineSDO);
        }
        //对于搭赠活动，需要对赠品选中的赠品进行排序
        Nullable.stream(activitySDOS).forEach(o->{
            if (CollectionUtils.isNotEmpty(o.getChooseGiftList())){
                List<GiftSDO> chooseGiftList =o.getChooseGiftList().stream().sorted(Comparator.comparing(GiftSDO::getSegOrderNo,Comparator.reverseOrder())).collect(Collectors.toList());
                o.setChooseGiftList(chooseGiftList);
            }
        });

        Map<String, Object> features = forecastOrderLineSDO.getFeatures();
        features.put(ForecastConstants.ACTIVITY_DETAILS, activitySDOS);
        Object activityCheckParams = features.get(ForecastConstants.ACTIVITY_CHECK_PARAMS);
        if (Objects.nonNull(activityCheckParams)){
            JSONObject activityCheckParamsMap = JSONObject.parseObject(JSONObject.toJSONString(activityCheckParams));
            List<ActivityItemInfoRequest> itemList = activityCheckParamsMap.getJSONArray(ForecastConstants.ITEM_LIST).toJavaList(ActivityItemInfoRequest.class);
            if (CollectionUtils.isNotEmpty(itemList)){
                for (ActivityItemInfoRequest activityItemInfoRequest : itemList) {
                    if (activityItemInfoRequest.getItemId().equals(forecastOrderLineSDO.getScItemId())){
                        activityItemInfoRequest.setItemQuantity((long)forecastOrderLineSDO.getPredictReplyAmount());
                    }
                }
            }
            activityCheckParamsMap.put(ForecastConstants.ITEM_LIST,itemList);
            features.put(ForecastConstants.ACTIVITY_CHECK_PARAMS,activityCheckParamsMap);
        }

        //修改活动id
        forecastOrderLineSDO.setActivityCode(activityCode);
        //修改活动名称
        forecastOrderLineSDO.setActivityName(activityName);
        orderLineSDOList.add(forecastOrderLineSDO);
        ForecastOrderSDO forecastOrderSDO = forecastOrderSDOMap.get(forecastOrderLineSDO.getMainOrderId());
//        ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.load(forecastOrderLineSDO.getMainOrderId());
        forecastOrderSDO.setForecastOrderLineSDOList(orderLineSDOList);
        //构造entity
        ForecastOrderEntity forecastOrderEntities = ForecastOrderEntity.of(forecastOrderSDO);
        return forecastOrderEntities;
    }

    public static ForecastOrderEntity updateActivityForecastObsolete(ForecastOrderActivityObsoleteRequest forecastOrderActivityRequest, Map<String, ForecastOrderLineSDO> forecastOrderLineMap, Map<String, ForecastOrderSDO> forecastOrderSDOMap) {
        //补全活动赠品价格数据兜底逻辑
        giftPriceCompletedObsolete(forecastOrderActivityRequest);

        //这里是实体，但里面只挂了一个子单
        String forecastOrderLineId = forecastOrderActivityRequest.getForecastOrderLineId();
        if (StringUtils.isEmpty(forecastOrderLineId)) {
            return null;
        }
        //根据子订单id查询出所有的子订单
        List<ForecastOrderLineSDO> orderLineSDOList = new ArrayList<>();
        ForecastOrderLineSDO forecastOrderLineSDO = forecastOrderLineMap.get(forecastOrderLineId);
//        ForecastOrderLineSDO forecastOrderLineSDO = forecastOrderLineQueryRepository.query(forecastOrderLineId);
        String activityName = "";
        String activityCode = "";
        List<ActivitySDO> activitySDOS = new ArrayList<>();
        List<ActivitySDO> activitySDOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(forecastOrderActivityRequest.getActivityChooseList())) {
            activitySDOList = forecastOrderActivityRequest.getActivityChooseList().stream().filter(i ->
                    StringUtils.isNotEmpty(i.getActivityCode())).collect(Collectors.toList());
        }
        // if(CollectionUtils.isNotEmpty(activitySDOList)) {
        activitySDOList = convertActivity(activitySDOList, forecastOrderLineSDO);
        // }
        log.info("新老活动匹配，转换后的活动列表：{}", activitySDOList);
        if (CollectionUtils.isNotEmpty(activitySDOList)) {
//            拼接活动名称
            List<String> activityNames = activitySDOList.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityName).collect(Collectors.toList());
            activityName = activityNames.stream().collect(Collectors.joining("/"));

//            拼接活动码
            List<String> activityCodes = activitySDOList.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityCode).collect(Collectors.toList());
            activityCode = activityCodes.stream().collect(Collectors.joining("/"));
            boolean haveSpecialOfferPriceSelectFlag = false;
            for (ActivitySDO activitySDO : activitySDOList) {
                //修改回复数量
                forecastOrderLineSDO.setPredictReplyAmount(forecastOrderActivityRequest.getActivityDetailList().get(0).getPredictReplyAmount());
                if (ActivityTypeEnum.SPECIAL_OFFER_PRICE.getValue().equals(activitySDO.getActivityType())) {
                    if (Objects.nonNull(activitySDO.getIsSelect()) && activitySDO.getIsSelect()) {
                        //修改活动金额
                        forecastOrderLineSDO.setActivityPrice(activitySDO.getSpecialOfferPrice());
                        //设置活动总金额，只有特价活动有特价 活动特价
                        if (null != activitySDO.getSpecialOfferPrice() && StringUtils.isNotEmpty(forecastOrderLineSDO.getQuantity())) {
                            forecastOrderLineSDO.setTotalActivityFee(activitySDO.getSpecialOfferPrice() * Long.parseLong(forecastOrderLineSDO.getQuantity()));
                        }
                        haveSpecialOfferPriceSelectFlag = true;
                    }
//                    else {
//                        //不选中特价的时候，重置活动价和活动总金额
//                        removeActivityPrice(forecastOrderLineSDO);
//                    }
                }
                //修改活动赠品情况
                Map<String, Object> features = forecastOrderLineSDO.getFeatures();
                activitySDOS.add(activitySDO);
                features.put(ForecastConstants.ACTIVITY_TAG, 0);
            }

            if (!haveSpecialOfferPriceSelectFlag) {
                //不选中特价的时候，重置活动价和活动总金额
                removeActivityPrice(forecastOrderLineSDO);
            }

        } else {
            //没有选中任何活动，也要移除活动价相关的逻辑
            //不选中特价的时候，重置活动价和活动总金额

            //modify by myw,20220916 to 未选中任何活动移除所有活动信息
            removeActivityAllInfo(forecastOrderLineSDO);
//            removeActivityPrice(forecastOrderLineSDO);
        }

        //对于搭赠活动，需要对赠品选中的赠品进行排序
        Nullable.stream(activitySDOS).forEach(o->{
            if (CollectionUtils.isNotEmpty(o.getChooseGiftList())){
                List<GiftSDO> chooseGiftList =o.getChooseGiftList().stream().sorted(Comparator.comparing(GiftSDO::getSegOrderNo,Comparator.reverseOrder())).collect(Collectors.toList());
                o.setChooseGiftList(chooseGiftList);
            }
        });

        Map<String, Object> features = forecastOrderLineSDO.getFeatures();
        features.put(ForecastConstants.ACTIVITY_DETAILS, activitySDOS);
        Object activityCheckParams = features.get(ForecastConstants.ACTIVITY_CHECK_PARAMS);
        if (Objects.nonNull(activityCheckParams)){
            JSONObject activityCheckParamsMap = JSONObject.parseObject(JSONObject.toJSONString(activityCheckParams));
            List<ActivityItemInfoRequest> itemList = activityCheckParamsMap.getJSONArray(ForecastConstants.ITEM_LIST).toJavaList(ActivityItemInfoRequest.class);
            if (CollectionUtils.isNotEmpty(itemList)){
                for (ActivityItemInfoRequest activityItemInfoRequest : itemList) {
                    if (activityItemInfoRequest.getItemId().equals(forecastOrderLineSDO.getScItemId())){
                        activityItemInfoRequest.setItemQuantity((long)forecastOrderLineSDO.getPredictReplyAmount());
                    }
                }
            }
            activityCheckParamsMap.put(ForecastConstants.ITEM_LIST,itemList);
            features.put(ForecastConstants.ACTIVITY_CHECK_PARAMS,activityCheckParamsMap);
        }

        //修改活动id
        forecastOrderLineSDO.setActivityCode(activityCode);
        //修改活动名称
        forecastOrderLineSDO.setActivityName(activityName);
        orderLineSDOList.add(forecastOrderLineSDO);
        ForecastOrderSDO forecastOrderSDO = forecastOrderSDOMap.get(forecastOrderLineSDO.getMainOrderId());
//        ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.load(forecastOrderLineSDO.getMainOrderId());
        forecastOrderSDO.setForecastOrderLineSDOList(orderLineSDOList);
        //构造entity
        ForecastOrderEntity forecastOrderEntities = ForecastOrderEntity.of(forecastOrderSDO);
        return forecastOrderEntities;
    }

    /**
     * 移除活动价
     *
     * @param forecastOrderLineSDO
     */
    private static void removeActivityPrice(ForecastOrderLineSDO forecastOrderLineSDO) {
        forecastOrderLineSDO.setActivityPrice(null);
        forecastOrderLineSDO.setTotalActivityFee(null);
        forecastOrderLineSDO.setActivityPriceRemark(null);
        //添加移除活动价的标，在更新的分开更新
        forecastOrderLineSDO.getFeatures().put(ForecastConstants.REMOVE_ACTIVITY_PRICE, "true");
    }

    /**
     * 移除所有活动信息
     *
     * @param forecastOrderLineSDO
     */
    private static void removeActivityAllInfo(ForecastOrderLineSDO forecastOrderLineSDO) {
        forecastOrderLineSDO.setActivityPrice(null);
        forecastOrderLineSDO.setTotalActivityFee(null);
        forecastOrderLineSDO.setActivityPriceRemark(null);
        forecastOrderLineSDO.setActivityCode(null);
        forecastOrderLineSDO.setActivityName(null);
        //添加移除活动价的标，在更新的分开更新
        forecastOrderLineSDO.getFeatures().put(ForecastConstants.REMOVE_ACTIVITY_ALL_INFO, "true");
        //移除活动的小红点
        forecastOrderLineSDO.getFeatures().put(ForecastConstants.ACTIVITY_TAG, 0);
    }

    /**
     * 赠品价格补全
     *
     * @param forecastOrderActivityRequest 预报单活动请求
     */
    private static void giftPriceCompleted(ForecastOrderActivityRequest forecastOrderActivityRequest) {

        List<ActivitySDO> activitySDOList = new ArrayList<>();
        if (Objects.nonNull(forecastOrderActivityRequest.getGiftActivity())||Objects.nonNull(forecastOrderActivityRequest.getSpecialActivity())) {
            //赠品活动数据处理
            if (Objects.nonNull(forecastOrderActivityRequest.getGiftActivity())){
                ActivityDTO giftActivity = forecastOrderActivityRequest.getGiftActivity();
                if (giftActivity.getEnabled()
                        &&StringUtils.isNotBlank(giftActivity.getSelectedActivityCode())
                        &&CollectionUtils.isNotEmpty(giftActivity.getList())){
                    //标记选中活动
                    List<ActivitySDO> chooseGiftActivity = giftActivity.getList().stream().filter(o -> o.getActivityCode().equals(giftActivity.getSelectedActivityCode())).collect(Collectors.toList());
                    activitySDOList.addAll(chooseGiftActivity);
                }}

            //特价活动数据处理
            if (Objects.nonNull(forecastOrderActivityRequest.getSpecialActivity())){
                ActivityDTO specialActivity = forecastOrderActivityRequest.getSpecialActivity();
                if (specialActivity.getEnabled()
                        &&StringUtils.isNotBlank(specialActivity.getSelectedActivityCode())
                        &&CollectionUtils.isNotEmpty(specialActivity.getList())){
                    //标记选中活动
                    List<ActivitySDO> chooseSpecialActivity = specialActivity.getList().stream().filter(o -> o.getActivityCode().equals(specialActivity.getSelectedActivityCode())).collect(Collectors.toList());
                    activitySDOList.addAll(chooseSpecialActivity);

                }
            }
        }
        if (CollectionUtils.isEmpty(activitySDOList)) {
            return;
        }

        for (ActivitySDO activitySDO : activitySDOList) {
            //选中赠品活动，必须选中赠品。如果赠品为空，直接抛异常
            if (ActivityTypeEnum.BUY_GIFT.getValue().equals(activitySDO.getActivityType())
                    && CollectionUtils.isEmpty(activitySDO.getChooseGiftList())) {
                log.error("选中赠品活动，赠品列表不能为空！activitySDO=" + JSON.toJSONString(activitySDO));
                throw new FacadeException("OTS-04-001-00-15-036");
            }

            //赠品列表和选中的赠品列表不为空。 注意：强依赖前端传入的GiftList 中的赠品价格
            if (CollectionUtils.isNotEmpty(activitySDO.getGiftList())
                    && CollectionUtils.isNotEmpty(activitySDO.getChooseGiftList())) {

                Map<String, GiftSDO> map = activitySDO.getGiftList().stream().collect(
                        Collectors.toMap(o->o.getScItemId()+'-'+o.getGiftSalesUnitCode()+'-'+o.getGiftDisable(), Function.identity()));

                activitySDO.getChooseGiftList().forEach(chooseGift -> {
                    if (chooseGift.getGiftPrice() == null) {
                        String key = chooseGift.getScItemId() + '-' + chooseGift.getGiftSalesUnitCode() + '-' + chooseGift.getGiftDisable();
                        chooseGift.setGiftPrice(map.get(key).getGiftPrice());
                        chooseGift.setGiftSalesUnitCode(map.get(key).getGiftSalesUnitCode());
                        chooseGift.setGiftSalesUnit(map.get(key).getGiftSalesUnit());
                        chooseGift.setSegOrderNo(map.get(key).getSegOrderNo());
                    }
                });
            }
        }

    }

    /**
     * 赠品价格补全(过时的)
     *
     * @param forecastOrderActivityRequest 预报单活动请求
     */
    private static void giftPriceCompletedObsolete(ForecastOrderActivityObsoleteRequest forecastOrderActivityRequest) {

        List<ActivitySDO> activityChooseList = forecastOrderActivityRequest.getActivityChooseList();
        if (CollectionUtils.isEmpty(activityChooseList)) {
            return;
        }

        for (ActivitySDO activitySDO : activityChooseList) {
            //选中赠品活动，必须选中赠品。如果赠品为空，直接抛异常
            if (ActivityTypeEnum.BUY_GIFT.getValue().equals(activitySDO.getActivityType())
                    && CollectionUtils.isEmpty(activitySDO.getChooseGiftList())) {
                log.error("选中赠品活动，赠品列表不能为空！activitySDO=" + JSON.toJSONString(activitySDO));
                throw new FacadeException("OTS-04-001-00-15-036");
            }

            //赠品列表和选中的赠品列表不为空。 注意：强依赖前端传入的GiftList 中的赠品价格
            if (CollectionUtils.isNotEmpty(activitySDO.getGiftList())
                    && CollectionUtils.isNotEmpty(activitySDO.getChooseGiftList())) {

                Map<String, GiftSDO> map = activitySDO.getGiftList().stream().collect(
                        Collectors.toMap(o->o.getScItemId()+'-'+o.getGiftSalesUnitCode()+'-'+o.getGiftDisable(), Function.identity()));

                activitySDO.getChooseGiftList().forEach(chooseGift -> {
                    if (chooseGift.getGiftPrice() == null) {
                        String key = chooseGift.getScItemId() + '-' + chooseGift.getGiftSalesUnitCode() + '-' + chooseGift.getGiftDisable();
                        chooseGift.setGiftPrice(map.get(key).getGiftPrice());
                        chooseGift.setGiftSalesUnitCode(map.get(key).getGiftSalesUnitCode());
                        chooseGift.setGiftSalesUnit(map.get(key).getGiftSalesUnit());
                        chooseGift.setSegOrderNo(map.get(key).getSegOrderNo());
                    }
                });
            }
        }

    }


    private static List<ActivitySDO> convertActivity(List<ActivitySDO> activitySDOS, ForecastOrderLineSDO forecastOrderLineSDO) {
        //add by myw,20220916 未选中活动清空活动数据
        if (CollectionUtils.isEmpty(activitySDOS)){
            return null;
        }
        log.info("活动选中前，新的活动列表：{}", activitySDOS);
        Map features = forecastOrderLineSDO.getFeatures();
        List<ActivitySDO> activitySDOSOlds = new ArrayList<>();
        if (MapUtils.isNotEmpty(features)) {
            activitySDOSOlds = (JSONObject.parseArray(JSON.toJSONString(features.get(ForecastConstants.ACTIVITY_DETAILS)), ActivitySDO.class));
            log.info("原来的选中的活动，原来的活动列表={}", activitySDOSOlds);
            //如果原有的值为空代表新增
            if (CollectionUtils.isEmpty(activitySDOSOlds)) {
                for (ActivitySDO activitySDO : activitySDOS) {
                    activitySDO.setIsSelect(true);
                }
                return activitySDOS;
            }
            //如果新的值为空代表全部禁用
            if (CollectionUtils.isEmpty(activitySDOS) && CollectionUtils.isNotEmpty(activitySDOSOlds)) {
                for (ActivitySDO activitySDO : activitySDOSOlds) {
                    activitySDO.setIsSelect(false);
                }
                return activitySDOSOlds;
            }

            if (CollectionUtils.isNotEmpty(activitySDOS) && CollectionUtils.isNotEmpty(activitySDOSOlds)) {
                //当修改数量等于原来数量全量覆盖
                if (activitySDOS.size() == activitySDOSOlds.size()) {
                    for (ActivitySDO activitySDO : activitySDOS) {
                        activitySDO.setIsSelect(true);
                    }
                    return activitySDOS;
                } else {
//                    for (ActivitySDO activitySDOYuan : activitySDOSOlds) {
//                        for (ActivitySDO activitySDONew : activitySDOS) {
//                            //id相等覆盖原有的
//                            if (activitySDONew.getActivityCode().equals(activitySDOYuan.getActivityCode())) {
//                                activitySDONew.setIsSelect(true);
//                                activitySDOList.add(activitySDONew);
//                            }
//                        }
//                    }
//                    for (ActivitySDO activitySDOOld : activitySDOSOlds) {
//                        for (ActivitySDO activitySDONew : activitySDOS) {
//                            if (!(activitySDONew.getActivityCode().equals(activitySDOOld.getActivityCode()))) {
//                                activitySDOOld.setIsSelect(false);
//                                activitySDOList.add(activitySDOOld);
//                            }
//                        }
//                    }
                    activitySDOSOlds.stream().forEach(i -> i.setIsSelect(false));
                    Map<String, List<ActivitySDO>> activitySDOOldMap = Nullable.stream(activitySDOSOlds).collect(Collectors.groupingBy(ActivitySDO::getActivityCode));
                    for (ActivitySDO activitySDO : activitySDOS) {
                        List<ActivitySDO> activitySDOSold = activitySDOOldMap.get(activitySDO.getActivityCode());
                        //如果不是空的话 代表
                        if (CollectionUtils.isNotEmpty(activitySDOSold)) {
                            activitySDOSOlds.stream().filter(r -> r.getActivityCode().equals(activitySDOSold.get(0).
                                    getActivityCode())).forEach(i -> {
                                i.setIsSelect(true);
                                //用户输入覆盖之前old ChooseGiftList值
                                i.setChooseGiftList(activitySDO.getChooseGiftList());
                            });
                        }
                    }
                    return activitySDOSOlds;
                }
            }
        }
        return activitySDOSOlds;
    }

    public static ForecastOrderEntity deleteActivityForecast(DeleteActivityForecastRequest deleteActivityForecastRequest) {
        String forecastOrderLineId = deleteActivityForecastRequest.getId();
        if (StringUtils.isEmpty(forecastOrderLineId)) {
            return null;
        }
        //根据子订单id查询出所有的子订单
        List<ForecastOrderLineSDO> forecastOrderLineSDOS = new ArrayList<>();
        ForecastOrderLineSDO forecastOrderLineSDO = forecastOrderLineQueryRepository.query(forecastOrderLineId);
        //修改活动id
        forecastOrderLineSDO.setActivityCode("");
        //修改活动名称
        forecastOrderLineSDO.setActivityName("");
        //修改活动金额,这个不做设置
        forecastOrderLineSDO.setActivityPrice(0L);

        //修改活动总金额,这个不做设置
        forecastOrderLineSDO.setTotalActivityFee(0L);

        //修改活动赠品情况
        Map<String, Object> features = forecastOrderLineSDO.getFeatures();
        //删除赠品信息
        features.remove(ForecastConstants.GIFTLIST);
        //删除活动标识
        features.remove(ForecastConstants.ACTIVITY_TAG);
        //删除活动详情
        features.remove(ForecastConstants.ACTIVITY_DETAILS);
        forecastOrderLineSDOS.add(forecastOrderLineSDO);
        ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.load(forecastOrderLineSDO.getMainOrderId());
        forecastOrderSDO.setForecastOrderLineSDOList(forecastOrderLineSDOS);
        //构造entity
        ForecastOrderEntity forecastOrderEntities = ForecastOrderEntity.of(forecastOrderSDO);
        return forecastOrderEntities;
    }

    public static ForecastOrderEntity confirmForecastStatus(BatchCreateOrderRequest confirmForecastStatus, ConfirmForecastRequest confirmForecastRequest) {

        List<String> ids = new ArrayList<>();
        ids.add(confirmForecastStatus.getForecastOrderLineId());
        //获取单条子订单信息
        PageResult<List<ForecastOrderLineSDO>> listPageResult = forecastOrderLineQueryRepository.batchLoadList(ids);
        //根据主订单id查询主订单信息
        ForecastOrderLineSDO forecastOrderLine = JSONObject.parseObject(JSONObject.toJSONString(listPageResult.getContent().get(0)), ForecastOrderLineSDO.class);
        Integer totalRepalyQtys = forecastOrderLine.getActualTotalReplyAmount() == null ? 0 : forecastOrderLine.getActualTotalReplyAmount();
        if (null != confirmForecastStatus.getPredictReplyAmount()) {
            forecastOrderLine.setActualTotalReplyAmount(totalRepalyQtys + confirmForecastStatus.getPredictReplyAmount());
        }
        Map<String, Object> features = forecastOrderLine.getFeatures();
        if (StringUtils.isNotBlank(confirmForecastStatus.getOrderId()) && StringUtils.isNotBlank(confirmForecastStatus.getOrderBizId())) {
            if (null != features.get(ForecastConstants.ORDER_ID)) {
                List orderIds = (List) features.get(ForecastConstants.ORDER_ID);
                orderIds.add(confirmForecastStatus.getOrderId());
                features.put(ForecastConstants.ORDER_ID, orderIds);
            } else {
                List<String> orderIds = new ArrayList<>();
                orderIds.add(confirmForecastStatus.getOrderId());
                features.put(ForecastConstants.ORDER_ID, orderIds);

            }
            if (null != features.get(ForecastConstants.ORDER_BIZ_ID)) {
                List orderBizIds = (List) features.get(ForecastConstants.ORDER_BIZ_ID);
                orderBizIds.add(confirmForecastStatus.getOrderBizId());
                features.put(ForecastConstants.ORDER_BIZ_ID, orderBizIds);
            } else {
                List<String> orderBizIds = new ArrayList<>();
                orderBizIds.add(confirmForecastStatus.getOrderBizId());
                features.put(ForecastConstants.ORDER_BIZ_ID, orderBizIds);
            }
            features.put("orderCreateDate", DateUtils.formatDate(new Date()));
            features.put("orderCreateName", confirmForecastRequest.getOperatorName());
        }
        features.put(ForecastConstants.CONFIRM_MESSAGE, confirmForecastStatus.getMessage());
        forecastOrderLine.setFeatures(features);
        ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.load(forecastOrderLine.getMainOrderId());
        List<ForecastOrderLineSDO> list = new ArrayList<>();
        list.add(forecastOrderLine);
        forecastOrderSDO.setForecastOrderLineSDOList(list);

        ForecastOrderEntity of = ForecastOrderEntity.of(forecastOrderSDO);
        return of;

    }

    public static List<ForecastOrderEntity> summaryForecastOrder(SummaryForecastOrderRequest summaryForecastOrderRequest) {
        List<String> ids = summaryForecastOrderRequest.getIds();
        //根据子订单id查询出所有的子订单
        PageResult<List<ForecastOrderLineSDO>> pageResult = forecastOrderLineQueryRepository.batchLoadList(ids);
        //根据发货仓进行分组
        Map<String, List<ForecastOrderLineSDO>> collect = Nullable.stream(pageResult.getContent()).collect(Collectors.groupingBy(ForecastOrderLineSDO::getWarehouseArea));
        if (collect.keySet().size() > 1) {
            throw new FunctionException("OTS-04-001-00-15-016");
        }
        //根据货品进行分组
        Map<String, List<ForecastOrderLineSDO>> scitemMap = Nullable.stream(pageResult.getContent()).collect(Collectors.groupingBy(ForecastOrderLineSDO::getScItemId));
        List<ForecastOrderSDO> forecastOrderSDOList = new ArrayList<>();
        int countNumber = 0;
        for (String scitemId : scitemMap.keySet()) {
            //获取出每种商品对应的子订单
            List<ForecastOrderLineSDO> forecastOrderLineSDOS = scitemMap.get(scitemId);
            ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.load(forecastOrderLineSDOS.get(0).getMainOrderId());

            List<ForecastOrderLineSDO> newForecastOrderLineSDOS = new ArrayList<>();
            ForecastOrderLineSDO newForecastOrderLineSDO = new ForecastOrderLineSDO();
            for (ForecastOrderLineSDO forecastOrderLineSDO : forecastOrderLineSDOS) {
                //将所有的数量装换成为库存单位数量  并累加
                if (StringUtils.isEmpty(forecastOrderLineSDO.getQuantity()) || StringUtils.isEmpty(forecastOrderLineSDO.getUnitConvert())) {
                    throw new FunctionException("OTS-04-001-00-15-019");
                }
                if ((!ObjectUtils.isEmpty(forecastOrderLineSDO.getQuantity()) && !ObjectUtils.isEmpty(forecastOrderLineSDO.getUnitConvert()))) {
                    int number = Integer.parseInt(forecastOrderLineSDO.getQuantity()) * Integer.parseInt(forecastOrderLineSDO.getUnitConvert());
                    countNumber += number;
                }
            }
            BeanUtils.copyProperties(forecastOrderLineSDOS.get(0), newForecastOrderLineSDO);
            newForecastOrderLineSDO.setQuantity(String.valueOf(countNumber));
            newForecastOrderLineSDOS.add(newForecastOrderLineSDO);
            forecastOrderSDO.setForecastOrderLineSDOList(newForecastOrderLineSDOS);
            forecastOrderSDOList.add(forecastOrderSDO);
        }
        //构造entity
        List<ForecastOrderEntity> forecastOrderEntities = new ArrayList<>(forecastOrderSDOList.size());
        forecastOrderSDOList.forEach(forecastOrderSDO -> forecastOrderEntities.add(convertToForecastEntity(forecastOrderSDO)));
        return forecastOrderEntities;
    }
}
